In the Python programming language, everything is an object including strings. (Yes, everything!)
Python text objects (strings) are created using the Class String
. So how can you determine if an object is created from the String class?
You can think of using the method type(), which returns the type of object.
>>> def isExactlyAString(obj):
return type(obj) is type( '')
>>> isExactlyAString(1)
False
>>> isExactlyAString('1')
True
>>>
and also
>>> def isAString (obj):
try: obj + ''
except: return False
else: return True
>>> isAString(1)
False
>>> isAString('1')
True
>>> isAString({1})
False
>>> isAString(['1'])
False
>>>
Although there are no problems with the ideas and methods we can use, there is a better way: isinstance (obj, str)
Python 3.7.5 (default, Nov 20 2019, 09:21:52)
[GCC 9.2.1 20191008] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def isAString(obj):
... return isinstance(obj,str)
...
>>> isAString(1)
False
>>> isAString('1')
True
>>>
Top comments (0)