Friday, December 27, 2024
Google search engine
HomeLanguagesCheck if a variable is string in Python

Check if a variable is string in Python

While working with different datatypes, we might come across a time, when we need to test the datatype for its nature. This article gives ways to test a variable against the data type using Python. Let’s discuss certain ways how to check variable is a string.

Check if a variable is a string using isinstance() 

This isinstance(x, str) method can be used to test whether any variable is a particular datatype. By giving the second argument as “str”, we can check if the variable we pass is a string or not. 

Python3




# initializing string
test_string = "GFG"
 
# printing original string
print("The original string : " + str(test_string))
 
# using isinstance()
# Check if variable is string
res = isinstance(test_string, str)
 
# print result
print("Is variable a string ? : " + str(res))


Output:

The original string : GFG
Is variable a string ? : True

Check if a variable is a string using type() 

This task can also be achieved using the type function in which we just need to pass the variable and equate it with a particular type. 

Python3




# initializing string
test_string = "GFG"
 
# printing original string
print("The original string : " + str(test_string))
 
# using type()
# Check if variable is string
res = type(test_string) == str
 
# print result
print("Is variable a string ? : " + str(res))


Output:

The original string : GFG
Is variable a string ? : True

Method 3 : using the issubclass() method.

step-by-step approach

Initialize the variable test_string with a string value.
Print the original string using the print() method.
Check if the variable is a string using the issubclass() method with the following parameters: the type() of the variable and the str class.
Assign the result to a variable called res.
Print the result using the print() method.

Python3




# initializing string
test_string = "GFG"
 
# printing original string
print("The original string : " + str(test_string))
 
# using issubclass()
# Check if variable is string
res = issubclass(type(test_string), str)
 
# print result
print("Is variable a string ? : " + str(res))


Output

The original string : GFG
Is variable a string ? : True

The time complexity of both methods is O(1), and the auxiliary space required is also O(1) since we are only creating a single variable res to store the result.

RELATED ARTICLES

Most Popular

Recent Comments