Computer >> Computer tutorials >  >> Programming >> Python

Python - Check if a variable is string


During the data manipulation using python, we may need to ascertain the data type of the variable being manipulated. This will help us in applying the appropriate methods or functions to that specific data type. In this article we will see how we can find out if a variable is of string data type.

Using type()

The type() method evaluates the data type of the input supplied to it. We will directly take the variable as input to the type () method and evaluate the variable.

Example

var1 = "Hello"
var2 = 123
var3 = "123"

# using type()
res_var1 = type(var1) == str
res_var2 = type(var2) == str
res_var3 = type(var3) == str

# print result
print("Is variable a string ? : " + str(res_var1))
print("Is variable a string ? : " + str(res_var2))
print("Is variable a string ? : " + str(res_var3))

Output

Running the above code gives us the following result −

Is variable a string ? : True
Is variable a string ? : False
Is variable a string ? : True

Using isinstance()

We can also use the isistance method. Here we supply both the variable as well as the str parameter to check if the variable is of type string.

Example

var1 = "Hello"
var2 = 123
var3 = "123"
# using isstance()
res_var1 = isinstance(var1, str)
res_var2 = isinstance(var2, str)
res_var3 = isinstance(var3, str)
# print result
print("Is variable a string ? : " + str(res_var1))
print("Is variable a string ? : " + str(res_var2))
print("Is variable a string ? : " + str(res_var3))

Output

Running the above code gives us the following result −

Is variable a string ? : True
Is variable a string ? : False
Is variable a string ? : True