Python print object as a string | Example code

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 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)
print(s1)
print(type(s1))

s2 = str(b)
print(s2)
print(type(s2))

Output:

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
print(repr(Test()))

Output:

{‘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()
print(t)

Output: Member of Test

Source: stackoverflow.com

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

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.