Python check if value is string | Example code

The best way to checks if the value is a string or not in Python is using the isinstance() function. This method test whether any variable is a particular datatype. In our case testing a string type.

Python checks if the value is a string Example

You have to pass 2 arguments first string and the second is datatype to be tested.

test_string = "Python"

res = isinstance(test_string, str)

# print result
print("Is value a string ? : " + str(res))

Output:

Python check if value is string

You can also use the type() method but it will return the type of datatype not a test with a given type. To check with the string you have to use the equality operator.

test_string = "Python"

res = type(test_string) == str

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

Output: Is value a string ? : True

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

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.