1

Reading through "Learn Python the Hard Way", I have tried to modify exercise 6, in order to see what happens. Originally it contains:

x = "There are %d types of people." % 10  
binary = "binary"  
do_not = "don't"  
y = "Those who know %s and those who %s." % (binary, do_not)  
print "I said: %r." % x  
print  "I also said: '%s'." % y

and produces the output:

I said: 'There are 10 types of people.'.
I also said: 'Those who know binary and those who don't.'.

In order to see the differences between using %s and %r in the last line, I replaced it with:

print "I also said: %r." % y

and obtained now the output:

I said: 'There are 10 types of people.'.
I also said: "Those who know binary and those who don't.".

My question is: Why now there are the double quotes instead of the single quotes?

4

2 回答 2

6

Because Python is being smart about quoting.

You are asking for a string representation (%r uses repr()), which presents strings in a manner that is legal Python code. When you echo values in the Python interpreter, the same representation is used.

Because y contains a single quote, Python gives you double quotes to not have to escape that quote.

Python prefers to use single quotes for string representations, and uses double when needed to avoid escaping:

>>> "Hello World!"
'Hello World!'
>>> '\'Hello World!\', he said'
"'Hello World!', he said"
>>> "\"Hello World!\", he said"
'"Hello World!", he said'
>>> '"Hello World!", doesn\'t cut it anymore'
'"Hello World!", doesn\'t cut it anymore'

Only when I used both types of quotes, did Python start to use an escape code (\') for the single quote.

于 2013-06-01T14:48:24.830 回答
3

Because the string has a single quote in it. Python is compensating.

于 2013-06-01T14:48:16.930 回答