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.
# 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)) |
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.
# 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)) |
The original string : GFG Is variable a string ? : True
Recommended Posts:
- Python | Check if given string can be formed by concatenating string elements of list
- String slicing in Python to check if a string can become empty by recursive deletion
- Python | Check if string ends with any string in given list
- Python | Check if a given string is binary string or not
- Python | Check for URL in a String
- Python | Check for float string
- Python set to check if string is panagram
- Python | Check whether string contains only numbers or not
- Python Set | Check whether a given string is Heterogram or not
- Python | Check if string repeats itself
- Python | Check for ASCII string
- Python | Check if given string is numeric or not
- Python | Check for spaces in string
- Python | Check if string is a valid identifier
- Check if both halves of the string have same set of characters in Python
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.



