根据文档,它们基本上是可互换的。在使用时有没有风格上的原因选择一个而非另一个?
我喜欢在用于插值或自然语言消息的字符串周围使用双引号,而在小的类似符号的字符串周围使用单引号,但如果字符串包含引号或者我忘记规则,则会打破这些规则。即使不需要,我也使用三重双引号来定义文档字符串和原始字符串字面量来表示正则表达式。
例如:
LIGHT_MESSAGES = {
'English': "There are %(number_of_lights)s lights.",
'Pirate': "Arr! Thar be %(number_of_lights)s lights."
}
def lights_message(language, number_of_lights):
"""Return a language-appropriate string reporting the light count."""
return LIGHT_MESSAGES[language] % locals()
def is_pirate(message):
"""Return True if the given message sounds piratical."""
return re.search(r"(?i)(arr|avast|yohoho)!", message) is not None
因此没有区别。相反,人们会告诉你选择与上下文相匹配的样式,并保持一致。我也同意这个观点 - 补充说明,为这种事情制定“约定”是毫无意义的,因为你只会混淆任何新手。简单来说:字符串文字可以用匹配的单引号(')或双引号(")括起来。
我曾经更喜欢使用单引号 '
,特别是在处理 '''文档字符串'''
时,因为我认为 """这些会产生一些无用的内容"""
。另外,我的瑞士德语键盘上可以不用按下 Shift 键来输入 '
。
后来,我改变了使用三重引号来编写 """文档字符串"""
,以符合 PEP 257 的规范。
我支持Will的做法:
即使需要大量转义,我也会坚持这种做法。
我最喜欢的是使用单引号来标识变量或常量,因为这些内容会因为引号而更加突出。其他的做法只是为了让那些使用单引号的标识符更加突出。
"You're able to do this"
或者 'He said "Hi!"'
。 除此之外,你应该尽可能保持一致性(在模块内、在包内、在项目内、在组织内)。''
,较长的字符串使用""
可能会有所帮助(同样适用于其他不可互换的语言)。"
而不是'
,但两者之间的差异很小。唯一的例外是"""these"""
比'''these'''
更常见,根据我所见。三重引号注释是这个问题的一个有趣子话题。PEP 257规定了用三重引号来作为文档字符串。我通过谷歌代码搜索(Google Code Search)进行了快速检查,发现在Python中三重双引号比三重单引号流行大约10倍——在Google索引的代码中有130万种使用三重双引号的情况,而只有13.1万种使用三重单引号的情况。因此,在多行情况下,如果您使用三重双引号,您的代码可能会更容易被人们理解和接受。
"If you're going to use apostrophes,
^
you'll definitely want to use double quotes".
^
出于这个简单的理由,我总是在外面使用双引号。 总是
说到废话,如果您不得不使用转义字符来表示撇号,那么将字符串文字与 ' 流程化有什么意义呢?阅读小说会冒犯程序员吗?我无法想象高中英语课对您来说有多痛苦!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'
"""This is a string with "quotes""""
会引发 SyntaxError 的错误。该如何解决这种情况呢?(与 '''This is a string with 'quotes''''
相同) - dolma33'''这是一个带有“引号”的字符串'''
。 - jpmc26个人而言,我会坚持使用其中一种。这并不重要。如果你在合作中为任何一种引用提供自己的含义,只会让其他人感到困惑。
一般情况下我使用双引号,但没有特别的原因——可能只是出于在Java中的惯性习惯。
我猜你更有可能在内联字面字符串中使用撇号而不是双引号。