In this post, we will see what is a string in Python and how to check whether a given variable is a string or not.
Table of Contents
What is a string in Python?
A string
is one of the widely used data types in Python and it is utilized to represent the Unicode characters in a variable. A string can be declared with either double or single quotes and has great flexibility, meaning it can easily hold any sort of value.
Here, we show a simple example of how to declare a string.
1 2 3 |
print("web") # or print('web') |
How to check if a given variable is of the string type in Python?
- Using the
isinstance()
function. - Using the
type()
function.
Using the isinstance()
function.
The isinstance()
function can be utilized for checking whether any given variable is of the desired data type or not.
The isinstance(x, y)
function takes in two arguments.
- x: This is any given variable
- y: This here can be any data type that you want to check the variable for. In our case, the value of this will be
str
.
The following code uses the isinstance()
function to check if a given variable is of the string type in Python.
1 2 3 4 5 |
var1 = "football" sol = isinstance(var1, str) print("Is it a string? ", sol) |
The above code provides the following output:
We can simply utilize this function to check if a given variable is of the string type in Python. However, in Python 2, we can use the same function with the argument as a basestring
class.
A basestring
class, which is an abstract of both the unicode
and the str
class is utilized inside the isinstance()
function.
Here’s an example code that shows this abstract class to implement the task:
1 2 3 4 5 |
var1 = 'football' sol = isinstance(var1, basestring) print("Is it a string? ", sol) |
The above code provides the following output:
Further reading:
Using the type()
function.
The type()
function is utilized to simply get the data type of any given variable. The type()
variable can be utilized with basic ==
operator or even with the is
operator to check if a given variable is of the string type in Python.
The following code uses the type()
function to check if a given variable is of the string type in Python.
1 2 3 4 5 |
var1 = "football" sol = type(var1) == str print("Is it a string? ", sol) |
The above code provides the following output:
Check if function parameter is String
We can use above methods to test if function parameter is String or not.
Let’s write a function to find length of String if datatype is String. If it is not String, then ignore it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
str1 = 789 str2 = 'Java2blog' def length_of_string(strInput): # We can also use "if isinstance(inp, str)" if not isinstance(strInput, str): print('Input is not a String') else: print(len(strInput)) length_of_string(str1) length_of_string(str2) |
Output:
9
You can also use type() function rather than isInstance here.
That’s all about how to check if variable is String in Python