Explain Codes LogoExplain Codes Logo

How to check if type of a variable is string?

python
functions
best-practices
collections
Anton ShumikhinbyAnton Shumikhin·Sep 18, 2024
TLDR

For checking the type of a variable, Python provides a built-in function isinstance():

is_string = isinstance(my_variable, str)

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:

is_string = isinstance(my_variable, str) # Text, woot! is_binary = isinstance(my_variable, bytes) # Not text, but equally awesome.

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:

is_string = isinstance(my_variable, basestring) # Handles both str and unicode like a boss

For code that works nicely with both Python 2.x and 3.x, clever use of try-except provides a smooth transition:

try: string_types = basestring # Python 2.x except NameError: string_types = str # Python 3.x, they grow up so fast

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:

# Rookie mistake: is_string = type(my_variable) == str # Subclasses would feel neglected # Better: is_string = isinstance(my_variable, str) # Subclasses feel loved!

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:

acts_like_string = hasattr(my_variable, "__str__") # "I know kung fu." - my_variable

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():

all_strings = all(isinstance(item, str) for item in my_collection) # Cleared by security

To see if at least one item is a string, sub any() for all():

any_strings = any(isinstance(item, str) for item in my_collection) # "I've got one!"