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:
- Pad or fill a string by a variable in Python using f-string
- Python | Check if variable is tuple
- How to check if a Python variable exists?
- Count occurrences of a sub-string with one variable character
- Python | Set 6 (Command Line and Variable Arguments)
- __name__ (A Special variable) in Python
- Different ways to access Instance Variable in Python
- Python | Using variable outside and inside the class and method
- Python | Variable list slicing
- Python | Convert 1D list to 2D list of variable length
- Python | setting and retrieving values of Tkinter variable
- Python | Accessing variable value from code scope
- Protected variable in Python
- Python Program to swap two numbers without using third variable
- __file__ (A Special variable) in Python
- Python - Variable Operations Dictionary update
- Full domain Hashing with variable Hash size in Python
- PYTHONPATH Environment Variable in Python
- Unused local variable in Python
- Unused variable in for loop 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.

