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))
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)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.