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.
1 2 3 4 5 6 |
i = 5 # not str print(isinstance(i, str)) s="abc" # string print(isinstance(s, str)) |
Output:
1 2 3 4 |
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:
1 2 3 4 |
def process_string(input_str): print('Processing', input_str) |
If we have following code snippet to execute this function:
1 2 3 4 |
process_string('abc') process_string(100) |
The output will be:
1 2 3 4 |
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.
1 2 3 4 5 6 7 |
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:
1 2 3 4 |
process_string('abc') process_string(100) |
The output will be:
1 2 3 4 |
Processing abc Input Must be String |
We can use isinstance() function to check the type of any variable or function arguments.
Reference: isinstance() api doc