Python Check Variable is String

Filed Under: Python

Sometimes we want to check if the variable or input argument is String and then only perform further actions. We can use isinstance() function to verify that a variable is string or not.

Python Variable is String

Let’s look at a simple example to check if a variable is a string or not.


i = 5  # not str

print(isinstance(i, str))

s = 'abc'  # string

print(isinstance(s, str))

Output:


False
True

Python Function Input is String

If you look at above example, we are creating the variable so we already know its type. However, if we have to define a function to process input string then it’s a good idea to check if the input supplied is a string or not.

Let’s say we have a function defined as:


def process_string(input_str):
    print('Processing', input_str)

If we have following code snippet to execute this function:


process_string('abc')

process_string(100)

The output will be:


Processing abc
Processing 100

Since we don’t have validation in place for the input argument, our function is processing non-string arguments too.

If we want our function to run its logic for string argument only, then we can add a validation check using isinstance() function.


def process_string(input_str):
    if (isinstance(input_str, str)):
        print('Processing', input_str)
    else:
        print('Input Must be String')

Now when we call this function as:


process_string('abc')

process_string(100)

The output will be:


Processing abc
Input Must be String

We can use isinstance() function to check the type of any variable or function arguments.

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: isinstance() api doc

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages