Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 282
some1 Avatar asked Jan 24 '12 11:01

some1


People also ask

What is the difference between %S and %R in Python?

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.

What does %s indicate in Python?

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

What does %d and %s do in Python?

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.

What is %r in Python format?

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


1 Answers

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.

like image 190
shang Avatar answered Sep 27 '22 18:09

shang