-3

I'm reading "Learn Python the hard way" (by Zed Shaw) and it says that %r is used for "raw representation and debugging".

I'm sorry for such a uninformed question, but I have no idea what does it mean.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
  • 1
    It's the representation returned form the `repr` function. It's similar to `str` but intended for internal use rather than display. It can be useful to print an element regardless of its type. [related](http://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python) – Paul Rooney Feb 27 '17 at 01:38
  • @PaulRooney You can answer below – OneCricketeer Feb 27 '17 at 01:40
  • 1
    @cricket I'm expecting it to be shut down as a dupe at any moment, so didnt think an answer was appropriate – Paul Rooney Feb 27 '17 at 01:41

1 Answers1

0

So you know %s is used for most strings, that just calls str() over the variable that is formatted.

repr(), on the other hand is used for %r and will return the "raw string", which is easiest seen on string variables.

>>> print("%r vs. %s" % ('42','42'))
'42' vs. 42

Python printf String formatting

'r' - String (converts any Python object using repr()).
's' - String (converts any Python object using str()).

When it says it is useful for "debugging", imagine you had leading/trailing spaces in a string... the "raw" format would be more clear.

print("%r vs. %s" % ('  hello','  hello'))
'  hello' vs.   hello
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245