python – How to check if type of a variable is string?
python – How to check if type of a variable is string?
In Python 2.x, you would do
isinstance(s, basestring)
basestring
is the abstract superclass of str
and unicode
. It can be used to test whether an object is an instance of str
or unicode
.
In Python 3.x, the correct test is
isinstance(s, str)
The bytes
class isnt considered a string type in Python 3.
I know this is an old topic, but being the first one shown on google and given that I dont find any of the answers satisfactory, Ill leave this here for future reference:
six is a Python 2 and 3 compatibility library which already covers this issue. You can then do something like this:
import six
if isinstance(value, six.string_types):
pass # Its a string !!
Inspecting the code, this is what you find:
import sys
PY3 = sys.version_info[0] == 3
if PY3:
string_types = str,
else:
string_types = basestring,
python – How to check if type of a variable is string?
In Python 3.x or Python 2.7.6
if type(x) == str: