How to check if type of a variable is string?
You can use the type() function in Python to check the type of a variable.
You can use the type() function in Python to check the type of a variable. Here is a code snippet that demonstrates how to check if a variable is a string:
Check the type of a Python variable using the type function
x = "hello"
if type(x) == str:
print("x is a string")
else:
print("x is not a string")
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
Alternatively, you can use the isinstance() function to check if a variable is an instance of a certain type. Here is an example:
Check the type of a Python variable using the isinstance function
x = "hello"
if isinstance(x, str):
print("x is a string")
else:
print("x is not a string")Note that type() returns a type object, so the boolean result comes from the comparison == str. isinstance() directly returns a boolean. In Python, isinstance() is generally preferred because it correctly handles inheritance.