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
test_string = "GFG"
print ( "The original string : " + str (test_string))
res = isinstance (test_string, str )
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
test_string = "GFG"
print ( "The original string : " + str (test_string))
res = type (test_string) = = str
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
test_string = "GFG"
print ( "The original string : " + str (test_string))
res = issubclass ( type (test_string), str )
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.
Last Updated :
05 May, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...