Skip to content

Python print object as a string | Example code

  • by

Use str() and __repr()__ methods to print objects as a string in Python. The __str__ method is what gets called happens when you print it, and the __repr__ method is what happens when you use the repr() function (or when you look at it with the interactive prompt).

Python print an object as a string example

Simple example code.

Using str() method

# object of int
a = 99

# object of float
b = 100.0

# Converting to string
s1 = str(a)

s2 = str(b)


Python print object as a string

Use repr() to convert an object to a string

print(repr({"a": 1, "b": 2}))
print(repr([1, 2, 3]))

# Custom class
class Test:
    def __repr__(self):
        return "This is class Test"

# Converting custom object to
# string


{‘a’: 1, ‘b’: 2}
[1, 2, 3]
This is class Test

If no __str__ method is given, Python will print the result of __repr__ instead. If you define __str__ but not __repr__, Python will use what you see above as the __repr__, but still use __str__ for printing.

class Test:
    def __repr__(self):
        return "Test()"

    def __str__(self):
        return "Member of Test"

t = Test()

Output: Member of Test


Do comment if you have any doubts or suggestions on this object tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *