Fix Python – How to check if variable is string with python 2 and 3 compatibility [duplicate]

Question

Asked By – Randall Hunt

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"

Now we will see solution for issue: How to check if variable is string with python 2 and 3 compatibility [duplicate]


Answer

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)

This question is answered By – ecatmur

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0