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.

Example

Here is an example of using isinstance:

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

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
True

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.

Improve your Python skills fast

The fastest way to learn programming is with lots of practice. Learn a programming concept, then write code to test your understanding and make it stick. Try our online interactive Python course today—it's free!

Learn more about the course

Want to get better at Python quickly? Try our interactive lessons today! Memberships are 100% FREE this week only!