How to check if type of a variable is string? How to check if type of a variable is string? python 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 isn't 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 don't find any of the answers satisfactory, I'll 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 sixif isinstance(value, six.string_types):    pass # It's a string !!

Inspecting the code, this is what you find:

import sysPY3 = sys.version_info[0] == 3if PY3:    string_types = str,else:    string_types = basestring,


In Python 3.x or Python 2.7.6

if type(x) == str:


matomo