Python check for string | Example code

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.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.