How to check if a variable is a string in Python

By

Learn how to check if a variable is a string in Python using the type() function or isinstance(), comparing the value against the built-in str class.

~~~

You can check if a variable is a string in Python in two ways: comparing its type() to the str class, or calling isinstance(). Both work, and I’ll show you when to prefer one over the other.

The first way uses the type() function, passing the variable as an argument, and then comparing the result to the str class:

name = "Roger"
type(name) == str  # True

The second way uses isinstance(), passing 2 arguments: the variable, and the str class:

name = "Roger"
isinstance(name, str)  # True

Any non-string value fails both checks, as you’d expect:

age = 8
isinstance(age, str)  # False

Which one should you use?

My advice is to use isinstance(). The difference shows up with subclasses.

type() returns the exact class of the value. If someone defines a class that inherits from str, the type() comparison fails, while isinstance() still recognizes it as a string:

class UserId(str):
    pass

uid = UserId("abc123")

type(uid) == str  # False
isinstance(uid, str)  # True

In most programs a UserId should be usable anywhere a string is, so isinstance() gives you the answer you actually want. This is also what PEP 8 recommends for type comparisons.

The bytes pitfall

Here’s a case that trips people up. Data read from a file opened in binary mode, or received over a network socket, is bytes, not str. It prints almost like a string, but it fails the check:

data = b"Roger"
isinstance(data, str)  # False

If your check returns False when you swear you have a string, print type(data) and look at it. If you see bytes, decode it first:

text = data.decode("utf-8")
isinstance(text, str)  # True

Checking before using string methods

A common reason for this check is guarding code that calls string methods, when a value might be a string or something else, like None:

def shout(value):
    if isinstance(value, str):
        return value.upper()
    return ""

shout("hello")  # 'HELLO'
shout(None)     # ''

Without the guard, None.upper() raises AttributeError. The isinstance() check keeps the function safe with any input.

Tagged: Python · All topics
~~~

Related posts about python: