开发者

The last line of this python program uses both " and ' but I don't know why

开发者 https://www.devze.com 2023-03-27 16:13 出处:网络
Ok on this link it shows the last line of output that has \' around everything except the third sentence and I do not know why. This bothered me at the beginning and thought i开发者_如何学Pythont was

Ok on this link it shows the last line of output that has ' around everything except the third sentence and I do not know why. This bothered me at the beginning and thought i开发者_如何学Pythont was just a weird mistake but its on the "extra credit" so now I am even more curious.


This is because the %r formatter prints the argument in the form you may use in source code, which, for strings, means that it is quote-delimited and escaped. For boolean values, this is just True or False. To print the string as it is, use %s instead.

>>> print '%s' % '"Hello, you\'re"'         
"Hello, you're"
>>> print '%r' % '"Hello, you\'re"'                        
'"Hello, you\'re"'


python's repr() function, which is invoked by interpolating the %r formatting directive, has the approximate effect of printing objects the way they would appear in source code.

There are several ways to format strings in python source, using single or double quotes, with backslash escapes or as raw strings, as simple, single line strings or multi line strings (in any combination). Python picks only two ways to format strings, as single or double quoted, single line strings with escapes instead of raw.

Python makes a crude attempt at picking a minimal format, with a slight bias in favor of the single quote version (since that would be one fewer keystrokes on most keyboards).

The rules are very simple. If a string contains a single quote, but no double quotes, python prints the string as it would appear in python source if it were double quoted, Otherwise it uses single quotes.

Some examples to illustrate. Note for simplicity all of the inputs use triple quotes to avoid backslash escapes.

>>> ''' Hello world '''
' Hello world '
>>> ''' "Hello world," he said. '''
' "Hello world," he said. '
>>> ''' You don't say? '''
" You don't say? "
>>> ''' "Can't we all just get along?" '''
' "Can\'t we all just get along?" '
>>> 
0

精彩评论

暂无评论...
验证码 换一张
取 消