根据文档,它们几乎是可以互换的。是否有使用其中一种而不是另一种的风格原因?


当前回答

Python使用引号,就像这样:

mystringliteral1="this is a string with 'quotes'"
mystringliteral2='this is a string with "quotes"'
mystringliteral3="""this is a string with "quotes" and more 'quotes'"""
mystringliteral4='''this is a string with 'quotes' and more "quotes"'''
mystringliteral5='this is a string with \"quotes\"'
mystringliteral6='this is a string with \042quotes\042'
mystringliteral6='this is a string with \047quotes\047'

print mystringliteral1
print mystringliteral2
print mystringliteral3
print mystringliteral4
print mystringliteral5
print mystringliteral6

输出如下:

this is a string with 'quotes'
this is a string with "quotes"
this is a string with "quotes" and more 'quotes'
this is a string with 'quotes' and more "quotes"
this is a string with "quotes"
this is a string with 'quotes'

其他回答

三重引用的评论是这个问题的一个有趣的子主题。PEP 257为文档字符串指定了三引号。我使用谷歌代码搜索做了一个快速检查,发现Python中的三双引号大约是三单引号的10倍——在谷歌代码索引中出现1.3M vs 131K次。在多行情况下,如果你的代码使用三双引号,人们可能会更熟悉。

我选择使用双引号,因为它们更容易看到。

我只是用我当时喜欢的东西;这很方便,能够在两者之间切换心血来潮!

当然,在引用引用字符时,在两者之间切换可能并不是那么异想天开……

引用官方文件https://docs.python.org/2.0/ref/strings.html:

简单地说:字符串字面量可以包含在匹配的单引号(')或双引号(")中。

所以没有区别。相反,人们会告诉你选择与上下文相匹配的风格,并保持一致。我同意——补充说,试图为这类事情提出“惯例”是毫无意义的,因为你最终只会让任何新人感到困惑。

这可能是一种风格上的偏好。我刚刚检查了PEP 8,没有看到任何提到单引号和双引号。

我更喜欢单引号,因为它只有一个按键,而不是两个。也就是说,我不需要捣碎shift键来做单引号。