0
0
Pythonprogramming~5 mins

String representation methods in Python

Choose your learning style9 modes available
Introduction

String representation methods help show objects as readable text. This makes it easier to understand what an object contains when you print it or look at it.

When you want to print an object and see useful information about it.
When debugging to quickly check what data an object holds.
When logging object details to a file or console.
When you want to customize how your object looks as text.
When using objects in places that expect strings, like messages or reports.
Syntax
Python
class ClassName:
    def __str__(self):
        return 'string to show when printed'

    def __repr__(self):
        return 'string to show in debug or console'

__str__ is for a friendly, readable string.

__repr__ is for an official string, often used for debugging.

Examples
This prints a friendly message when the object is printed.
Python
class Person:
    def __str__(self):
        return 'Person named Alice'

p = Person()
print(p)
This shows a detailed string useful for debugging.
Python
class Person:
    def __repr__(self):
        return 'Person(name="Alice")'

p = Person()
print(repr(p))
Both methods can be defined to show different strings.
Python
class Person:
    def __str__(self):
        return 'Alice'
    def __repr__(self):
        return 'Person(name="Alice")'

p = Person()
print(p)       # Uses __str__
print(repr(p)) # Uses __repr__
Sample Program

This program shows how __str__ and __repr__ give different string views of the same object.

Python
class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author

    def __str__(self):
        return f'"{self.title}" by {self.author}'

    def __repr__(self):
        return f'Book(title={self.title!r}, author={self.author!r})'

book = Book('1984', 'George Orwell')
print(book)       # Calls __str__
print(repr(book)) # Calls __repr__
OutputSuccess
Important Notes

If __str__ is not defined, Python uses __repr__ as a fallback.

Use !r inside f-strings to get the repr() of a value.

Good string representations make your code easier to read and debug.

Summary

__str__ gives a nice, readable string for users.

__repr__ gives a detailed string for developers and debugging.

Defining these methods helps show objects clearly when printed or inspected.