Check Variable Type as 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. It is necessary to verify the type of a variable before performing the operations. For example, if we want to ensure that the variable is a string before using the string methods like upper(), lower().

If the variable is not of the expected type, calling these methods will raise an error. Python provides various ways to check if the variable is of type string. Let's dive into the article to learn more about it.

Using Python isinstance() Function

The first approach is by using the Python isinstance() function to check whether the variable is of type string. This function takes two arguments: the variable to be checked and the type to check against. It returns true if the input is true, otherwise, it returns false.

Syntax

Following is the syntax for Python isinstance() function -

isinstance(object, type)

Example 1

In the following example, we are going to consider the basic usage of the isinstance() function.

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

The output of the above program is as follows -

Checking if the given input is string or not
True

Example 2

Consider another scenario, where 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("Checking if the given input is string or not")
print(isinstance(str1, str))

The output of the above program is as follows -

Checking if the given input is string or not
False

Using Python type() Function

The second approach is by using the Python type() function to determine the type of variable.

In this case, the type() function checks the type of the variable, then compares it with the str class using the "==" operator. If the type of the value matches the str, it returns true, otherwise, it returns false.

Syntax

Following is the syntax for the Python type() function -

type(object, bases, dict)

Example

Following is an example where we are taking an input and checking if the given input is a string or not using the type() function.

str1 = "Welcome"
if type(str1) == str:
   print("The variable is a string.")
else:
   print("The variable is not a string.")

The following is the output of the above program -

The variable is a string.
Updated on: 2025-05-20T11:51:21+05:30

31K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements