Fundamentals 3 min read

Understanding Python’s !s and !r Format Specifiers and the Difference Between __str__ and __repr__

The article explains how Python’s !s and !r format specifiers invoke the __str__ and __repr__ methods respectively, illustrates their output differences with examples, and discusses when each representation is appropriate for debugging and readable string conversion.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Understanding Python’s !s and !r Format Specifiers and the Difference Between __str__ and __repr__

This article introduces the use of the !s and !r conversion flags in Python’s format strings, which call the object's __str__ and __repr__ methods respectively.

Example output demonstrates that !s produces a human‑readable string while !r yields a representation that includes quotes and can often be used to recreate the object.

>> 'foo {!s}'.format('bar')
'foo bar'
>>> 'foo {!r}'.format('bar')
"foo 'bar'"

The choice between __str__ and __repr__ depends on the object: if a class defines both, __str__ provides an informal, readable form, whereas __repr__ aims for an official representation that could be a valid Python expression.

When neither method is overridden, the default implementations inherited from object are used, with __repr__ typically returning a string like <ClassName object at 0x...> and __str__ delegating to __repr__.

These representations are primarily useful for debugging; __repr__ should be detailed and unambiguous, while __str__ should be concise and user‑friendly.

In format strings, the !s conversion flag selects the __str__ result and !r selects the __repr__ result, allowing explicit control over how values are formatted.

Fundamentals__str__String Formatting__repr__
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.