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

PythonServer Side ProgrammingProgramming

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
raja
Published on 14-Dec-2017 10:42:09
Advertisements