0

I've recently started to learn python and do not understand %r and %s. What is the difference between the two? Analogies would be greatly appreciated. I've tried to problem solve and see how the two work. I created simple code to understand strings within python but it doesn't seem to work. What is wrong with the code below and what is the correct way of doing it? Also can you show step by step what you are doing in the CORRECT code? Thank you for helping an amateur learn python.

formatter = "%r %r %r %r"
print "Here are the days: formatter" % ('Monday','Tuesday','Wednesday','Thursday')
  • 1
    You included `formatter` as a literal string rather than a variable, that's why that likely doesn't work, so `print formatter % (...)` – OneCricketeer Jun 13 '16 at 16:33
  • @John Smith your code works fine, as cricket_007 points out you just need to use `formatter` as a variable: `print "Here are the days: ", formatter % ('Monday','Tuesday','Wednesday','Thursday')` – chickity china chinese chicken Jun 13 '16 at 16:38

2 Answers2

0

The problem with you code is, that you are not adding the formatter varibale to the string, but the literal string. To fix this use:

formatter = "%r %r %r %r"
print "Here are the days: " + formatter % ('Monday','Tuesday','Wednesday','Thursday')

Now about %s and %r: The difference is, that %r uses the __repr__ method to convert your object to a string and %s uses __str__. For in-depth information about the difference of __repr__ and __str__ you can look at this answer: https://stackoverflow.com/a/2626364/5189673

And the formatter just take the elements of the tuple, uses their __repr__ (as %r is used) to convert them to a strings and then replaces the %rs with the acquired strings.

Community
  • 1
  • 1
Leon
  • 2,926
  • 1
  • 25
  • 34
0

In you example the difference between %s and %r would be

>>> print "Here are the days: %s %s %s %s" % ('Monday', ...
Here are the days: Monday Tuesday Wednesday Thursday

vs

>>> print "Here are the days: %r %r %r %r" % ('Monday', ...
Here are the days: 'Monday' 'Tuesday' 'Wednesday' 'Thursday'

Notice the quotation marks to denote a string in the %r example. In general, the repr conversion (ie. %r) is used when you want the output to be valid python. This can be because you want to eval the output, or maybe you want to save the output so it can be evaluated later.

Brendan Abel
  • 35,343
  • 14
  • 88
  • 118