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

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

If youre writing 2.x-and-3.x-compatible code, youll probably want to use six:

from six import string_types
isinstance(s, string_types)

The most terse approach Ive found without relying on packages like six, is:

try:
  basestring
except NameError:
  basestring = str

then, assuming youve been checking for strings in Python 2 in the most generic manner,

isinstance(s, basestring)

will now also work for Python 3+.

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

What about this, works in all cases?

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

Leave a Reply

Your email address will not be published. Required fields are marked *