How to check if type of a variable is string?

c_pleaseUpvote picture c_pleaseUpvote · Jan 30, 2011 · Viewed 952.2k times · Source

Is there a way to check if the type of a variable in python is a string, like:

isinstance(x,int);

for integer values?

Answer

Sven Marnach picture Sven Marnach · Jan 30, 2011

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.