Computer >> Computer tutorials >  >> Programming >> Python

How to check if type of a variable is string in Python?


We can use the isinstance(var, class) to check if the var is instance of given class. In Python 2.x the base class of str and unicode is basestring. So we can use it as follows:

>>> s = 'A string'
>>> isinstance(s, basestring)
True
>>> isinstance(s, str)
True
>>> isinstance(10, basestring)
False


Note: In Python 3.x, basestring is not defined, hence we have to use str instead of it. For example:

>>> s = 'A string'
>>> isinstance(s, str)
True
>>> isinstance(10, str)
False