Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
When to use %r instead of %s in Python?
In Python, string formatting can be done using the % formatting operator. The %s uses str() to convert values, while %r uses repr() to convert values. Understanding when to use each is crucial for debugging and logging.
Key Differences
-
%s: Converts the value to a human-readable string using
str() -
%r: Converts the value to its representation using
repr(), showing quotes, escape characters, etc.
When to Use %r
Use %r when you need to see the exact representation of a value, including escape characters, quotes, and whitespace. This is particularly useful for:
- Debugging strings with hidden characters
- Logging exact values
- Understanding data structure contents
Example 1: Handling Escape Characters
Here we compare how %s and %r handle newline characters ?
text = "TP\nTutorialsPoint"
print("Using %%s: %s" % text)
print("Using %%r: %r" % text)
Using %s: TP TutorialsPoint Using %r: 'TP\nTutorialsPoint'
Notice how %s interprets the newline while %r shows the raw escape sequence.
Example 2: Debugging Whitespace Issues
When debugging strings with leading/trailing spaces, %r makes them visible ?
text = " TutorialsPoint "
print("Using %%s: %s" % text)
print("Using %%r: %r" % text)
Using %s: TutorialsPoint Using %r: ' TutorialsPoint '
The %r clearly shows the surrounding quotes and spaces that might be invisible with %s.
Example 3: Data Structures
For data structures without special characters, both operators produce similar output ?
cars = ["RX100", "Ciaz", "Chiron"]
print("Using %%s: %s" % cars)
print("Using %%r: %r" % cars)
Using %s: ['RX100', 'Ciaz', 'Chiron'] Using %r: ['RX100', 'Ciaz', 'Chiron']
Practical Use Cases
| Scenario | Use %s | Use %r |
|---|---|---|
| User-facing output | ? | ? |
| Debug logging | ? | ? |
| Show exact string content | ? | ? |
| Pretty display | ? | ? |
Conclusion
Use %r for debugging and logging when you need to see the exact representation of values. Use %s for user-friendly display and general string formatting.
