To check if a variable is a string, you can use the type() function and check if the variable is of type string.

t = "string"
a = 1
l = [0, 1, 2]

print(type(t) == str)
print(type(a) == str)
print(type(l) == str)

#Output:
True
False
False

You can also use the isinstance() function to check if a variable is a string.

t = "string"
a = 1
l = [0, 1, 2]

print(isinstance(t,str))
print(isinstance(a,str))
print(isinstance(l,str))

#Output:
True
False
False

When working with different types of variables in Python, the ability to check the type of the variables easily is valuable.

One such case is if you want to check if a variable is a string in your Python code.

To check if a variable is of type string, you can use the type() function.

type() returns the class type of the argument passed.

If type() returns str, then we can conclude the variable is a string.

Below are some examples showing you how to check if a variable is a string in Python.

t = "string"
a = 1
l = [0, 1, 2]

print(type(t) == str)
print(type(a) == str)
print(type(l) == str)

#Output:
True
False
False

Using isinstance() to Check if Variable is String in Python

One other way you can check if a variable is of type string is with the isinstance() function.

isinstance() checks to see if a variable is an instance of the class passed.

Below is an example showing you how to use isinstance() in Python to check if a variable is string.

t = "string"
a = 1
l = [0, 1, 2]

print(isinstance(t,str))
print(isinstance(a,str))
print(isinstance(l,str))

#Output:
True
False
False

Hopefully this article has been useful for you to check if a variable is a string in Python.

Categorized in:

Python,

Last Update: March 11, 2024