%s vs %r: String Formatting में Difference
%s Specifier Object को str() का उपयोग करके Convert करता है, और %r इसे repr() का उपयोग करके Convert करता है।
कुछ Objects जैसे Integers के लिए, वे Same Result देते हैं, लेकिन repr() इसमें Special है कि (उन Types के लिए जहां यह संभव है) यह Conventionally ऐसा Result Return करता है जो Valid Python Syntax होता है, जिसे Unambiguously उस Object को Recreate करने के लिए उपयोग किया जा सकता है जिसे यह Represent करता है।
उदाहरण: Newline Characters के साथ
>>> string = "Hello\nworld"
>>> print("Example: %s" % string)
Example: Hello
world
>>> print("Example: %r" % string)
Example: 'Hello\nworld'
%s Actual Newline Print करता है, जबकि %r Escape Sequence \n दिखाता है और Quotes भी Intact रखता है।
आप Second Expression का उपयोग Object को Actually Recreate करने के लिए कर सकते हैं।
Key Differences:
| Aspect | %s (str) | %r (repr) |
|---|---|---|
| Purpose | Human-readable Output | Unambiguous Representation |
| Quotes | No | Yes (Strings के लिए) |
| Escape Sequences | Processed | Shown as Escapes |
| Recreatable | Usually No | Yes (Ideally) |
When to Use Each:
- %s: User-facing Output, Logs, Display
- %r: Debugging, Logging (Developer-facing), repr() Implementation
Custom Classes में __repr__ और __str__:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"({self.x}, {self.y})"
def __repr__(self):
return f"Point({self.x}, {self.y})"
p = Point(3, 4)
print("%s" % p) # (3, 4)
print("%r" % p) # Point(3, 4)