Python | Check if a variable is string

While working with different datatypes, we might come across a time, where we need to test the datatype for its nature. This article gives ways to test a variable against the data type it is. Let’s discuss certain ways in which this task can be done.

Method #1 : Using isinstance(x, str)

This 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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# Check if variable is string 
# using isinstance()
  
# 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))

chevron_right


Output :

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

 

Method #2 : Using type()

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

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# Check if variable is string 
# using type()
  
# 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))

chevron_right


Output :

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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.