1

Well, i just always use %r on python, but I don't know when I have to use these other formats...

mahr
  • 59
  • 1
  • 1
  • 5

2 Answers2

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