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


当前回答

我的目标是最小化像素和惊喜。我通常更喜欢' in order to最小化像素,但是' '如果字符串有撇号,同样是为了最小化像素。然而,对于文档字符串,我更喜欢"""而不是" ',因为后者是不标准的、不常见的,因此令人惊讶。如果现在我有一堆字符串,我使用“根据上面的逻辑,但也可以使用一个',我可能仍然使用”,以保持一致性,只是为了尽量减少惊喜。

也许用以下方式来思考像素最小化哲学会有所帮助。你更希望英文字符看起来像A B C还是AA BB CC?后一种选择浪费了50%的非空像素。

其他回答

就我个人而言,我坚持两者之一。没关系。当你们合作的时候,为这两句话提供自己的意思只会让其他人感到困惑。

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

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

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

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'
"If you're going to use apostrophes, 
       ^

you'll definitely want to use double quotes".
   ^

出于这个简单的原因,我总是在外面使用双引号。总是

说到无用,如果你必须使用转义字符来表示撇号,那么用'简化字符串文字有什么好处呢?读小说会冒犯程序员吗?我无法想象高中英语课对你来说有多痛苦!