How to check if variable is string with python 2 and 3 compatibility

If you're writing 2.x-and-3.x-compatible code, you'll probably want to use six:

from six import string_types
isinstance(s, string_types)

The most terse approach I've found without relying on packages like six, is:

try:
  basestring
except NameError:
  basestring = str

then, assuming you've been checking for strings in Python 2 in the most generic manner,

isinstance(s, basestring)

will now also work for Python 3+.


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.


What about this, works in all cases?

isinstance(x, ("".__class__, u"".__class__))