
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python - Check if a variable is string
During the data manipulation using python, we may need to ascertain the data type of the variable being manipulated. This will help us in applying the appropriate methods or functions to that specific data type. In this article we will see how we can find out if a variable is of string data type.
Using type()
The type() method evaluates the data type of the input supplied to it. We will directly take the variable as input to the type () method and evaluate the variable.
Example
var1 = "Hello" var2 = 123 var3 = "123" # using type() res_var1 = type(var1) == str res_var2 = type(var2) == str res_var3 = type(var3) == str # print result print("Is variable a string ? : " + str(res_var1)) print("Is variable a string ? : " + str(res_var2)) print("Is variable a string ? : " + str(res_var3))
Output
Running the above code gives us the following result −
Is variable a string ? : True Is variable a string ? : False Is variable a string ? : True
Using isinstance()
We can also use the isistance method. Here we supply both the variable as well as the str parameter to check if the variable is of type string.
Example
var1 = "Hello" var2 = 123 var3 = "123" # using isstance() res_var1 = isinstance(var1, str) res_var2 = isinstance(var2, str) res_var3 = isinstance(var3, str) # print result print("Is variable a string ? : " + str(res_var1)) print("Is variable a string ? : " + str(res_var2)) print("Is variable a string ? : " + str(res_var3))
Output
Running the above code gives us the following result −
Is variable a string ? : True Is variable a string ? : False Is variable a string ? : True
- Related Articles
- How to check if type of a variable is string in Python?
- Check if variable is tuple in Python
- Check if a string is Colindrome in Python
- How do I check if a Python variable exists?
- Python - Check if a given string is binary string or not
- Check if a string is Pangrammatic Lipogram in Python
- How to check if a string is alphanumeric in Python?
- Check if a string is Isogram or not in Python
- Check if a string is suffix of another in Python
- Check if a given string is a valid number in Python
- How to check if a string in Python is in ASCII?
- Python program to check if a string is palindrome or not
- Python program to check if a given string is number Palindrome
- How to check if a string is a valid keyword in Python?
- Python program to check if the string is pangram

Advertisements