Skip to content

Python check for string | Example code

  • by

Use the isinstance() method to check for a string in Python. This method can be used to test whether any variable is a particular (string) datatype or not. If yes then return True.

isinstance(give_string, str)

Python check for string Example code

Python code to demonstrate check if the variable is a string using isinstance().

test_string = "The original string"
res = isinstance(test_string, str)

print("Is variable a string ? : " + str(res))

Output:

Python check for string

Another method

In Python 3.x or Python 2.7.6 use the type method.

if type(x) == str:

Complete code

var2 = 'this is variable #2'
if type(var2) == str:
    print('your variable is a string')
else:
    print('your variable IS NOT a string')

Output: your variable is a string

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading