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. Here is a code snippet that demonstrates how to check if a variable is a string:
x = "hello"
if type(x) == str:
print("x is a string")
else:
print("x is not a string")Alternatively, you can use the isinstance() function to check if a variable is an instance of a certain type. Here is an example:
x = "hello"
if isinstance(x, str):
print("x is a string")
else:
print("x is not a string")Both type() and isinstance() will return true if the variable is string.