根据文档,它们几乎是可以互换的。是否有使用其中一种而不是另一种的风格原因?
当前回答
我喜欢在用于插值的字符串或自然语言消息的字符串周围使用双引号,而对于像符号一样的小字符串使用单引号,但如果字符串包含引号,或者如果我忘记了,就会破坏规则。我对文档字符串使用三双引号,对正则表达式使用原始字符串字面量,即使它们不需要。
例如:
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
其他回答
如果字符串包含其中一个,则应该使用另一个。例如,“你能做这个”,或者“他说了“嗨!”。除此之外,你应该尽可能保持一致(在一个模块内,在一个包内,在一个项目内,在一个组织内)。
如果您的代码将被使用C/ c++的人阅读(或者如果您在这些语言和Python之间切换),那么使用“用于单字符字符串,使用“”用于较长的字符串可能有助于简化转换。(同样也适用于其他不可互换的语言)。
我在野外看到的Python代码倾向于“over”,但只是略微倾向于这样。唯一的例外是,“”“这些”“”比“这些”更常见,从我所看到的。
我选择使用双引号,因为它们更容易看到。
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'
我以前更喜欢',特别是'文档字符串',因为我发现''' '这会产生一些绒毛''' '。此外,在我的瑞士德语键盘上,'也可以不用Shift键输入。
为了符合PEP 257,我已经将“”“文档字符串”“”改为使用三引号。
就我个人而言,我坚持两者之一。没关系。当你们合作的时候,为这两句话提供自己的意思只会让其他人感到困惑。