How to check if type of a variable is string?
In Python 2.x, you would do
basestring is the abstract superclass of
unicode. It can be used to test whether an object is an instance of
In Python 3.x, the correct test is
bytes class isn't considered a string type in Python 3.
I know this is an old topic, but being the first one shown on google and given that I don't find any of the answers satisfactory, I'll leave this here for future reference:
six is a Python 2 and 3 compatibility library which already covers this issue. You can then do something like this:
import sixif isinstance(value, six.string_types): pass # It's a string !!
Inspecting the code, this is what you find:
import sysPY3 = sys.version_info == 3if PY3: string_types = str,else: string_types = basestring,