How to find out if a Python object is a string?

Viewed 392849

How can I check if a Python object is a string (either regular or Unicode)?

15 Answers

Its simple, use the following code (we assume the object mentioned to be obj)-

if type(obj) == str:
    print('It is a string')
else:
    print('It is not a string.')

I think it's safe to assume that if the final character of the output of repr() is a ' or ", then whatever it is, it aught to be considered some kind of string.

def isStr(o):
    return repr(o)[-1] in '\'"'

I'm assuming that repr won't be doing anything too heavy and that it'll return a string of at least one character. You can support empty strings by using something like

repr(o)[-1:].replace('"', "'") == "'"

but that's still assuming repr returns a string at all.

Related