How to find out if a Python object is a string?

PythonServer Side ProgrammingProgramming

For Python 2.x

To check if an object obj is a string type or a subclass of a string type −

isinstance(obj, basestring)

because both str and unicode are subclasses of basestring.

To check if obj is an instance of str or any subclass of str −

isinstance(obj, str)

To check if obj is an instance of unicode string −

isinstance(obj, unicode)

For Python 3.x, just

isinstance(obj, str)

works for both str and unicode strings.

Published on 23-Jan-2018 18:41:38