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

Solution 1:

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)

Solution 2:

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+.