Well, i just always use %r on python, but I don't know when I have to use these other formats...
Asked
Active
Viewed 6.0k times
1
-
1http://docs.python.org/2/library/string.html#format-examples – Daniel Mar 02 '13 at 03:27
-
That certainly exists on the Internet somewhere – thescientist Mar 02 '13 at 03:28
-
http://stackoverflow.com/questions/8986179/python-the-hard-way-exercise-6-r-versus-s – grc Mar 02 '13 at 03:35
-
Well, at least `str.format` is marginally clearer about these. – Mike DeSimone Mar 02 '13 at 03:43
2 Answers
16
This is explained in the Python documentation. In short,
%d
will format a number for display.%s
will insert the presentation string representation of the object (i.e.str(o)
)%r
will insert the canonical string representation of the object (i.e.repr(o)
)
If you are formatting an integer, then these are equivalent. For most objects this is not the case.

James Henstridge
- 42,244
- 6
- 132
- 114
11
Here is an example to supplement James Henstridge's answer:
class Cheese(float):
def __str__(self):
return 'Muenster'
def __repr__(self):
return 'Stilton'
chunk = Cheese(-123.4)
print(str(chunk))
# Muenster
print(repr(chunk))
# Stilton
print(int(chunk))
# -123
print('%s\t%r\t%d'%(chunk, chunk, chunk))
# Muenster Stilton -123

unutbu
- 842,883
- 184
- 1,785
- 1,677