How to Check if Variable is String in Python
In Python, use the
isinstance() function to check if a variable is a string by writing isinstance(variable, str). This returns True if the variable is a string, otherwise False.Syntax
The syntax to check if a variable is a string uses the isinstance() function.
variable: the value you want to check.str: the string type in Python.- The function returns
Trueifvariableis a string, otherwiseFalse.
python
isinstance(variable, str)
Example
This example shows how to check different variables to see if they are strings.
python
variable1 = "Hello" variable2 = 123 variable3 = ['a', 'b', 'c'] print(isinstance(variable1, str)) # True because variable1 is a string print(isinstance(variable2, str)) # False because variable2 is an integer print(isinstance(variable3, str)) # False because variable3 is a list
Output
True
False
False
Common Pitfalls
Some common mistakes when checking if a variable is a string include:
- Using
type(variable) == strwhich works but is less flexible thanisinstance(). - Confusing strings with other types like bytes or lists.
- Not considering subclasses of
strif you usetype()instead ofisinstance().
python
variable = "Hello" # Less flexible way (not recommended) print(type(variable) == str) # True # Recommended way print(isinstance(variable, str)) # True
Output
True
True
Quick Reference
| Check Method | Description |
|---|---|
| isinstance(variable, str) | Returns True if variable is a string or subclass of string |
| type(variable) == str | Returns True only if variable is exactly a string type |
| isinstance(variable, (str, bytes)) | Checks if variable is string or bytes type |
Key Takeaways
Use isinstance(variable, str) to check if a variable is a string in Python.
isinstance() is preferred over type() for flexibility and subclass support.
The check returns True only if the variable is a string or subclass of string.
Avoid confusing strings with other types like bytes or lists.
Use quick reference table to remember different checking methods.