How to check if type of a variable is string in Python?


In this article, we are going to find out how to check if the type of a variable is a string in Python.

The first approach is by using the isinstance() method. This method takes 2 parameters, the first parameter being the string that we want to test and the next parameter is the keyword str. This method will return True if the given input is a string, otherwise, it returns False.

It specifies that when we pass an object and class, or tuple of classes, to the isinstance() method, it will return True if the object's data type matches the class provided and False otherwise.

Example 1

In the example given below, we are taking input and checking whether it is a string or not using the isinstance() method and printing if the input is a string or not 

str1 = "Tutorialspoint"

print("The given string is")
print(str1)

print("Checking if the given input is string or not")
print(isinstance(str1, str))

Output

The output of the above example is as shown below −

The given string is
Tutorialspoint
Checking if the given input is string or not
True

Example 2

In the example given below, we are taking the same program as above but with different input and checking the type of the input and printing if the input is a string or not.

str1 = 10

print("The given string is")
print(str1)

print("Checking if the given input is string or not")
print(isinstance(str1, str))

Output

The output of the above example is given below −

The given string is
10
Checking if the given input is string or not
False

Using type() method

The second approach is by using the inbuilt method type(). This method takes an input and returns the type of the given input. We will return True if the type is string otherwise return False.

Example 1

In the example given below, we are taking an input and checking if the given input is string or not using type() method and printing if the input is a string or not 

str1 = "Tutorialspoint"

print("The given string is")
print(str1)

print("Checking if the given input is a string or not")
print(type(str1) == str)

Output

The output of the above example is as shown below −

The given string is
Tutorialspoint
Checking if the given input is a string or not
True

Example 2

In the example given below, we are taking the same program as above but we are taking a different input and we are checking if it belongs to string or not 

str1 = 10

print("The given string is")
print(str1)

print("Checking if the given input is string or not")
print(type(str1) == str)

Output

The output of the above example is given below −

The given string is
10
Checking if the given input is string or not
False

Updated on: 07-Dec-2022

25K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements