The best way to checks if the object is a string is by using the isinstance() method in Python. This function returns True if the given object is an instance of class classified or any subclass of class info, otherwise returns False.
How to find out if a Python object is a string Example
Let’s see simple python example code for a given variable is of string type or not. In the example using if-else for condition check.
An object is a string if it has the type str.
sample_text = "Hello" if isinstance(sample_text, str): print('Type of variable is a string') else: print('Type is variable is not a string')
Another example using type() function
You can also use the type() function to check if the type of a variable object is a string in python.
sample_text = "Hello" if type(sample_text) == str: print('Type of Object is string') else: print('Type of Object is not string')
Output: Type of Object 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)
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.