Ways to check if a variable is a string in Python.
With the problem of checking the datatype for its nature arises the need to check if a variable is a string in Python.
In this tutorial, we demonstrate the several ways available to us that help in checking whether a given string is of the string
data type.
Using the isinstance()
function.
The isinstance()
function aids in the completion of a simple task. It is capable of checking whether any given variable that can be provided as an input to this function is of a certain data type which is desired by the user or not.
The isinstance(x, y)
function mainly has just two arguments,
-
x: The variable that needs to be checked.
-
y: Specifies the value of any data type that we want to check the variable against.
Consider the following code.
# For newer versions of Python( > Python 2.7). a = "Autism" c = isinstance(a, str) print("True if it's a string :", c) # Output: True if it's a string : True
We can make a few tweaks to the above code to make it work in Python 2. We make use of the basestring
keyword instead of the str
keyword that we had been using in the above code.
A basestring
class can be defined as an abstract of both the str
class and the unicode
.
Consider the following code.
# For Python 2 a = 'Autism' c = isinstance(a, basestring) print("True if it's a string :", c) # Output : ('True if it's a string :', True)
Using the type()
function.
The type()
function is capable of getting in the data type in all the cases. Moreover, it has a simple syntax as it is utilized with the simple ==
operator. Alternatively, the is
operator also works fine with the type()
function.
Consider the following code.
a = "Autism" c = type(a) == str print("True if it's a string :", c) # Output: True if it's a string : True
To Conclude.
Explore more from this category at Python Strings. Alternatively, search and view other topics at All Tutorials.