Skip to content

Python check if value is string | Example code

  • by

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.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 *