Skip to content

Python if variable is string | Example code

  • by

There are two ways to check if a variable is a string in Python. First isinstance() method and second type() method.

How to check if a variable is a string in Python

Simple python examples code:

Using isinstance(var, str)

The isinstance function takes two arguments. The first is your variable. The second is the type you want to check for. In our case, we are testing string type so the second parameter will be a string type.

var = "a string"

print(isinstance(var, str))

Output:

Python if variable is string

Using type() – Alternative approach

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

var = "a string"

print(type(var))

Output:

How to check if a variable is a string in Python

Do comment if you have any doubts and suggestions on this Python string topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

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