Open In App

Convert Object to String in Python

Last Updated : 28 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Python provides built-in type conversion functions to easily transform one data type into another. This article explores the process of converting objects into strings which is a basic aspect of Python programming.

Since every element in Python is an object, we can use the built-in str() and repr() methods to convert any built-in object into a string representation. Let’s see how these methods work with the help of an example.

str() method

str() is a built-in method so don’t need to import any library, we can simple use it over the targeted object.

i = 6   # int object
a = [1, 2, 3, "Hello"]  # list object

# Converting to string
s1 = str(i)
print(s1)
print(type(s1))

s2= str(a)
print(s2)
print(type(s2))

Output
6
<class 'str'>
[1, 2, 3, 'Hello']
<class 'str'>

repr() method

repr() method is a bit different from str(), it gives a more detailed string representation of an object. Unlike str(), which focuses on making output user-friendly, repr() provides a more technical view which is helpful for debugging and often includes object type or structure and its also customizable. Let’s looks at some examples,

Example 1: Normal list conversion

# Using repr() with a list

a = [1, 2, 3, "Hello"]

print(repr(a))
print(type(repr(a)))

Output
[1, 2, 3, 'Hello']
<class 'str'>

Example 2: Converting objects of user defined classes with and without “__repr__()” method.

# Class without __repr__()
class Animal:
    def __init__(self, species, sound):
        self.species = species
        self.sound = sound

# Class with __repr__()
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __repr__(self):
        return f"Person(name='{self.name}', age={self.age})"

# Creating objects
a = Animal("Dog", "Bark")
p = Person("Prajjwal", 22)

# Using repr() on both objects
print("Without __repr__():", repr(a))
print("With __repr__():", repr(p))

Output
Without __repr__(): <__main__.Animal object at 0x7f2b98ac2900>
With __repr__(): Person(name='Prajjwal', age=22)

Explanation:

  • Without __repr__(): Python uses a default format, which just shows the object’s type and memory address (something like <__main__.Animal object at 0x7f9d8c3f2d30>).
  • With __repr__(): The object gets a more meaningful and readable description, based on what we define in the __repr__() method.

Note: To know a lot more interesting things about str() and repr() and the difference between them, refer to str() vs repr() in Python



Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg