Python中的单引号和双引号
根据文档的说明,这两个基本上是可以互换使用的。那么,有没有什么风格上的原因让我们选择用其中一个而不是另一个呢?
19 个回答
90
我以前更喜欢用 '
,特别是在写 '''docstrings'''
的时候,因为我觉得 """this creates some fluff"""
看起来有点多余。而且在我的瑞士德语键盘上,打 '
不需要按 Shift 键。
不过后来我改用了三重引号 """docstrings"""
,这样可以符合 PEP 257 的规范。
96
引用官方文档的内容,地址是 https://docs.python.org/2.0/ref/strings.html:
简单来说:字符串可以用匹配的单引号(')或双引号(")括起来。
所以其实没有什么区别。人们通常会建议你根据具体情况选择使用哪种风格,并且要保持一致性。我也同意这个观点——我觉得试图为这种事情制定“规范”是没必要的,因为这样只会让新手更加困惑。
525
我喜欢在需要插入变量或者是自然语言消息的字符串周围使用双引号,而对于一些小的符号类字符串则用单引号。不过如果字符串里有引号,或者我忘记了,我就会打破这个规则。我会用三重双引号来写文档字符串,用原始字符串来处理正则表达式,即使有时候并不需要这样做。
举个例子:
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