gpt4 book ai didi

python - 字符串表示中的双引号

转载 作者:太空狗 更新时间:2023-10-29 18:30:50 28 4
gpt4 key购买 nike

这段代码:

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

运行时,打印这个字符串:

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

为什么 “But it didn't sing.” 在其他三个项目用单引号引起来时用双引号引起来?

(此代码取自 Learn Python the Hard Way Exercise 8 。)

最佳答案

Python 很聪明;在生成表示时,它将对包含单引号的字符串使用双引号,以尽量减少转义:

>>> 'no quotes'
'no quotes'
>>> 'one quote: \''
"one quote: '"

在那里也添加一个双引号,它将恢复为单引号并转义包含的任何单引号:

>>> 'two quotes: \'\"'
'two quotes: \'"'

关于python - 字符串表示中的双引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11917043/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com