Check if Variable Is String in Python

Check if variable is String in Python

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.

There are many options in Python when it comes to making a choice of selecting a data type and this sometimes creates a need This tutorial focuses on and demonstrates the different ways available to check if a given variable is of the string type in Python.

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.

How to check if a given variable is of the string type in Python?

  1. Using the isinstance() function.
  2. 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.

The above code provides the following output:

Is it a string? True

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:

The above code provides the following output:

(‘Is it a string? ‘, True)

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.

The above code provides the following output:

Is it a string? True

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.

Output:

Input is not a String
9

You can also use type() function rather than isInstance here.

That’s all about how to check if variable is String in Python

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *