Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to check if type of a variable is string in Python?
In Python, it is essential to verify the type of a variable before performing operations on it. For example, if you want to use string methods like upper() or lower(), you need to ensure the variable is actually a string to avoid errors.
Python provides several ways to check if a variable is of type string. Let's explore the most common approaches.
Using isinstance() Function
The isinstance() function is the recommended approach to check variable types in Python. It takes two arguments: the variable to check and the type to check against, returning True if the variable matches the specified type.
Syntax
isinstance(object, type)
Example 1: String Variable
Here's how to check if a variable contains a string ?
text = "Tutorialspoint"
print("Checking if the variable is a string:")
print(isinstance(text, str))
print(f"Type: {type(text).__name__}")
Checking if the variable is a string: True Type: str
Example 2: Non-String Variable
Let's test with a non-string variable ?
number = 42
print("Checking if the variable is a string:")
print(isinstance(number, str))
print(f"Type: {type(number).__name__}")
Checking if the variable is a string: False Type: int
Using type() Function
The type() function returns the exact type of a variable. You can compare it directly with the str class using the equality operator.
Syntax
type(object)
Example
Here's how to use type() for string checking ?
variables = ["Welcome", 123, 45.67, True]
for var in variables:
if type(var) == str:
print(f"'{var}' is a string")
else:
print(f"'{var}' is {type(var).__name__}, not a string")
'Welcome' is a string '123' is int, not a string '45.67' is float, not a string 'True' is bool, not a string
Comparison of Methods
| Method | Inheritance Support | Best Practice | Use Case |
|---|---|---|---|
isinstance() |
Yes | ? Recommended | General type checking |
type() |
No | Limited use | Exact type matching |
Practical Example
Here's a practical function that safely processes string variables ?
def process_text(data):
if isinstance(data, str):
return data.upper().strip()
else:
return f"Error: Expected string, got {type(data).__name__}"
# Test with different data types
test_values = [" hello world ", 123, None, "Python"]
for value in test_values:
result = process_text(value)
print(f"Input: {value} ? Output: {result}")
Input: hello world ? Output: HELLO WORLD Input: 123 ? Output: Error: Expected string, got int Input: None ? Output: Error: Expected string, got NoneType Input: Python ? Output: PYTHON
Conclusion
Use isinstance(variable, str) for checking string types as it's the recommended approach in Python. The type() method works but doesn't handle inheritance properly. Always validate variable types before performing type-specific operations to prevent runtime errors.
