Skip to content
Related Articles
Open in App
Not now

Related Articles

Check if a variable is string in Python

Improve Article
Save Article
Like Article
  • Difficulty Level : Basic
  • Last Updated : 23 Mar, 2023
Improve Article
Save Article
Like Article

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

My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!