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

Randall Hunt picture Randall Hunt · Jul 2, 2012 · Viewed 82.1k times · Source

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) work as expected in python-2.x? Or will I need to check the version and use isinstance(x, basestr)?

Specifically, in python-2.x:

>>>isinstance(u"test", str)
False

and python-3.x does not have u"foo"

Answer

ecatmur picture ecatmur · Jul 2, 2012

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)