Python Principles

How to check if a variable is a string

To check if a variable contains a value that is a string, use the isinstance built-in function.

The isinstance function takes two arguments. The first is your variable. The second is the type you want to check for.


Here is an example of using isinstance:

>>> var = "a string"
>>> isinstance(var, str)

Alternative approach

You can also use the type built-in function to see if the type of your variable is str. For example:

>>> type(var)
<type 'str'>
>>> type(var) == str

So you could write something like this:

if type(var) == str:
    print("it's a string!")

Check if a string is a valid number

If you want to see if your variable can be converted to a number, refer to this post.