Python check if the object is string | example code

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.

isinstance(object, class) 

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.

isinstance(string_object, str) 

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')

Output:

Python check if the object is 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.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.