The difference between %s and %r is that %s uses the str function and %r uses the repr function. You can read about the differences between str and repr in this answer, but for built-in types, the biggest difference in practice is that repr for strings includes quotes and all special characters are escaped.
%r is not a valid placeholder in the str. format() formatting operations; it only works in old-style % string formatting. It indeed converts the object to a representation through the repr() function.
%s specifically is used to perform concatenation of strings together. It allows us to format a value inside a string. It is used to incorporate another string within a string. It automatically provides type conversion from value to string.
They are used for formatting strings. %s acts a placeholder for a string while %d acts as a placeholder for a number. Their associated values are passed in via a tuple using the % operator.
The %s
specifier converts the object using str()
, and %r
converts it using repr()
.
For some objects such as integers, they yield the same result, but repr()
is special in that (for types where this is possible) it conventionally returns a result that is valid Python syntax, which could be used to unambiguously recreate the object it represents.
Here's an example, using a date:
>>> import datetime
>>> d = datetime.date.today()
>>> str(d)
'2011-05-14'
>>> repr(d)
'datetime.date(2011, 5, 14)'
Types for which repr()
doesn't produce Python syntax include those that point to external resources such as a file
, which you can't guarantee to recreate in a different context.
Use the %r
for debugging, since it displays the "raw" data of the variable,
but the others are used for displaying to users.
That's how %r
formatting works; it prints it the way you wrote it (or close to it). It's the "raw" format for debugging. Here \n
used to display to users doesn't work. %r
shows the representation if the raw data of the variable.
months = "\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
print "Here are the months: %r" % months
Output:
Here are the months: '\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug'
Check this example from Learn Python the Hard Way.
%r
shows with quotes:
It will be like:
I said: 'There are 10 types of people.'.
If you had used %s
it would have been:
I said: There are 10 types of people..
This is a version of Ben James's answer, above:
>>> import datetime
>>> x = datetime.date.today()
>>> print x
2013-01-11
>>>
>>>
>>> print "Today's date is %s ..." % x
Today's date is 2013-01-11 ...
>>>
>>> print "Today's date is %r ..." % x
Today's date is datetime.date(2013, 1, 11) ...
>>>
When I ran this, it helped me see the usefulness of %r.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With