I\'m aware that I can use: isinstance(x, str) in python-3.x but I need to check if something is a string in python-2.x as well. Will isinstance(x, str)
This is @Lev Levitsky's answer, re-written a bit.
try:
isinstance("", basestring)
def isstr(s):
return isinstance(s, basestring)
except NameError:
def isstr(s):
return isinstance(s, str)
The try/except test is done once, and then defines a function that always works and is as fast as possible.
EDIT: Actually, we don't even need to call isinstance(); we just need to evaluate basestring and see if we get a NameError:
try:
basestring # attempt to evaluate basestring
def isstr(s):
return isinstance(s, basestring)
except NameError:
def isstr(s):
return isinstance(s, str)
I think it is easier to follow with the call to isinstance(), though.