Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Check if a Python Object is a String



A group of objects is called a class. The class is a blueprint, which is used as the reference to create the object. This contains attributes and methods in a logical entity.

Let's understand the usage of the class in an object-oriented programming language through a real-time scenario.

  • Consider a library. In a library, we will have different numbers of books. Now we want to track every book from the library.

  • For a book, we will have different attributes like book name, specialization, etc. Let's say the list holds the details of the book. The first element will be the book name, and the second element will be the specialization of the book.

  • If there are 1000 books in the library, we cannot analyze which element is related to which book.

  • And it is difficult as we want to add a new element to a particular book. So in these cases, we will use classes to have better organization.

If we want to check the datatype of an object, to determine whether it is a string or not, we have different methods. Let's see them one by one.

Using the isinstance() method

One of the methods to check whether the instance is a string or not is the instance method. The following syntax can be used to check if the instance is a string or not.

isinstance(obj, basestring)

Example

Let's see an example to check whether the given instance is a string or not. The following code can be used to check if the instance is a string or not.

tstring = "python"
print("The original string : " + str(tstring))
# using isinstance()
# Check if variable is string 
res = isinstance(tstring, str)
# print result
print("Is instance a string ? : " + str(res))

The following is the output of the isinstance() method. We can observe the output in the binary format.

The original string : python
Is instance a string ? : True

Using the type() method

We can also determine whether a particular object is a string or not, using the type() method.Following is the syntax of this method -

type(obj, basestring)

Example

Let's see an example to check whether the given instance is a string or not by using the type method. The following code can be used for checking if the instance is string or not.

tstring = "python"
print("The original string : " + str(tstring))
# using isinstance()
# Check if variable is string 
res = (type(tstring)== str)
# print result
print("Is instance a string ? : " + str(res))

Following is an output of the above code ?

The original string : python
Is instance a string ? : True
Updated on: 2025-05-29T11:24:49+05:30

329 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements