Python the Hard Way – exercise 6 – %r versus %s

Question:

http://learnpythonthehardway.org/book/ex6.html

Zed seems to use %r and %s interchangeably here, is there any difference between the two? Why not just use %s all the time?

Also, I wasn’t sure what to search for in the documentation to find more info on this. What are %r and %s called exactly? Formatting strings?

Asked By: some1

||

Answers:

%r calls repr, while %s calls str. These may behave differently for some types, but not for others: repr returns “a printable representation of an object”, while str returns “a nicely printable representation of an object”. For example, they are different for strings:

>>> s = "spam"
>>> print(repr(s))
'spam'
>>> print(str(s))
spam

In this case, the repr is the literal representation of a string (which the Python interpreter can parse into a str object), while the str is just the contents of the string.

Answered By: Fred Foo

%s invokes str(), whereas %r invokes repr(). For details, see Difference between __str__ and __repr__ in Python

Answered By: NPE

They are called string formatting operations.

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.

Answered By: shang

The code below illustrates the difference. Same value prints differently:

x = "xxx"
withR = "prints with quotes %r"
withS = "prints without quotes %s"
Answered By: AnnSwers
 x = "example"
 print "My %s"%x

       My example

 print "My %r"%x

       My 'example'

It is well explained in the above answers. I have tried to show the same with a simple example.

Answered By: misguided

The following is a summary of the preceding three code examples.

# First Example
s = 'spam'
# "repr" returns a printable representation of an object,
# which means the quote marks will also be printed.
print(repr(s))
# 'spam'
# "str" returns a nicely printable representation of an
# object, which means the quote marks are not included.
print(str(s))
# spam

# Second Example.
x = "example"
print ("My %r" %x)
# My 'example'
# Note that the original double quotes now appear as single quotes.
print ("My %s" %x)
# My example

# Third Example.
x = 'xxx'
withR = ("Prints with quotes: %r" %x)
withS = ("Prints without quotes: %s" %x)
print(withR)
# Prints with quotes: 'xxx'
print(withS)
# Prints without quotes: xxx
Answered By: S. Newton

%s => string

%r => exactly as is

Using the code in the book:

my_name = 'Zed A. Shaw'
print "Let's talk about %s." % my_name
print "Let's talk about %r." % my_name

we get

Let's talk about Zed A. Shaw.
Let's talk about 'Zed A. Shaw'.
Answered By: Snowcrash
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.