简体   繁体   中英

Double vs. single quotes using formatted printing in python

So I was going through "Learn Python the Hard Way"

and while doing this:

formatter = "%r %r %r %r"

print formatter % (
    "I had this thing.",
    "That you could up right.",
    "But it didn't sing.",
    "So I said goodnight"
)

the output was

'I had this thing.' 'That you could up right.' "But it didn't sing." 'So I said goodnight'

But I'm not sure why the 3rd string has double strings.

"a" and 'a' are the same strings, no difference.

The third string contains an apostrophe, so it cannot be represented as 'But it didn't sing.' because that would end the string after didn and raise a SyntaxError .

If you want to represent a string with single quote, you can do it:

"'"

or

'\''

The same with double quote:

'"'

or

"\""

If you have a string with both quotes, you can choose one:

'"\'"

or

"\"'"

Because the third string would be 'But it didn't sing' - this would provide a syntax error due to three apostrophes, and furthermore, if fixed logically(putting one more ' in the end which would remove the error), you'd be stuck with two strings - 1. 'But it didn' and 2. 't sing' , which is not correct.

So to answer your question, "" provide the exact same function in strings but is used when a syntax error could be caused, such as for words like didn't, couldn't, or the like in the English language.

第三个字符串中有一个'字符,这就是为什么"用于表示它。尝试从字符串#3中删除' ,你会看到表示更改为'字符串' 。字符串是相同的,它只是一个区别他们的代表。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM