How to check if type of a variable is string?
For checking the type of a variable, Python provides a built-in function isinstance():
This will return True if my_variable is a string and False otherwise. The best part is that, isinstance() will consider inheritance (subclasses), a key Python feature.
Python 3.x vs. Python 2.x: The bytes and unicode saga
Strings in Python 3.x
Python 3.x treats str as text data and bytes as binary data. These are two distinct types:
Juggling str, unicode, and basestring in Python 2.x
In Python 2.x, we've got str and unicode. The abstract parent class for both is basestring:
For code that works nicely with both Python 2.x and 3.x, clever use of try-except provides a smooth transition:
Now, use string_types with isinstance() to keep your code ready for any Py-version party.
Don't fall into the type() trap
type() isn't recommended for string checking, as it overlooks subclasses. Here's an example:
Remember, subclasses can include user-defined classes or types from libraries. Ignoring these could be like stepping on a python (pun intended).
Edge cases you'll want to master
Handling string-like classes
Objects can have string-like behavior without being subclasses of str. To account for this, you might check for string functionality:
But watch out, some non-string objects might have a __str__ function for completely unrelated reasons.
String check for collections
Checking if all items in a collection are strings? Marry isinstance() with all():
To see if at least one item is a string, sub any() for all():
Was this article helpful?