Checking if a variable is a string in Python is a common requirement when validating user input, processing form data, or working with different data types. Python provides several ways to perform this check, but the most reliable and idiomatic approach is the built-in isinstance() function.
Using isinstance() to Check If a Variable Is a String
The isinstance() function determines whether an object belongs to a specified type or one of several possible types. To check if a variable is a string, pass the variable and the str type to the function:
name = "Python"
print(isinstance(name, str))
The output is:
True
The first argument is the object being checked, while the second argument is the expected type. Because str is Python’s built-in string type, isinstance(name, str) returns True when name contains a string and False otherwise.
You can also store the result in a variable:
value = "Hello, world!"
is_string = isinstance(value, str)
print(is_string)
This approach is recommended for most applications because it is clear, efficient, and correctly recognizes string subclasses Simple, but easy to overlook. Nothing fancy..
Checking a Variable with type()
Another way to check whether a variable is a string is to compare its type with str:
value = "Hello"
print(type(value) is str)
This also returns True for a normal string.
The slightly older comparison below works as well:
print(type(value) == str)
Even so, using type(value) is str is generally considered more precise because is checks whether both objects are the same object. Here, type(value) returns the string type itself, and str is that same type object.
The main difference between type(value) is str and isinstance(value, str) is that isinstance() accepts subclasses of str, while an exact type comparison does not Most people skip this — try not to..
The Difference Between isinstance() and an Exact Type Check
Consider a custom class that inherits from str:
class Username(str):
pass
username = Username("alex")
print(isinstance(username, str)) # True
print(type(username) is str) # False
The username object behaves like a string because it inherits from str. That said, its exact type is Username, not str.
Choose the method based on your requirement:
- Use
isinstance(value, str)when a string or any string subclass should be accepted. - Use
type(value) is strwhen only an exact built-in string is allowed. - Avoid using
value.__class__for this purpose because direct access to__class__can be misleading and is less idiomatic.
For ordinary application code, isinstance(value, str) is usually the best choice Not complicated — just consistent..
Checking Multiple Allowed Types
The isinstance() function can also check whether a variable belongs to a group of types. Pass a tuple containing the acceptable types:
value = "Python"
print(isinstance(value, (str, int, float)))
The result is True because value is a string and strings are included in the allowed types The details matter here. Surprisingly effective..
This is useful when validating data that may legitimately have several forms:
def process_identifier(identifier):
if not isinstance(identifier, (str, int)):
raise TypeError("Identifier must be a string or an integer.")
return identifier
Keep in mind that checking multiple types does not make a non-string object into a string. It only confirms that the object belongs to at least one of the permitted categories.
Checking Values That Are Not Strings
The function works with any Python object:
number = 42
price = 19.99
active = True