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?
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.
%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.
%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.
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.
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