Python Check Variable is String With Example

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.


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:

If we have following code snippet to execute this function:

The output will be:

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.

Now when we call this function as:

The output will be:

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

By admin

Leave a Reply

%d bloggers like this: