Python中的单引号与双引号

2024-04-24 20:08:30 发布

您现在位置:Python中文网/ 问答频道 /正文

根据文献记载,它们几乎可以互换。有没有一个文体上的原因要用一个来代替另一个?


Tags: andthetopicisthisarebutits
3条回答

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

In plain English: String literals can be enclosed in matching single quotes (') or double quotes (").

所以没有区别。相反,人们会告诉你选择与上下文匹配的样式,并保持一致。我也同意-补充说,试图为这类事情想出“惯例”是没有意义的,因为你最终只会混淆任何新来者。

我以前更喜欢',尤其是'''docstrings''',我发现"""this creates some fluff"""。而且,'也可以在不使用瑞士德语键盘上的Shift键的情况下键入。

我后来改为对"""docstrings"""使用三重引号,以符合PEP 257

我喜欢在用于插值或自然语言消息的字符串周围使用双引号,而对于小符号(如字符串)则使用单引号,但如果字符串包含引号或忘记了,则会破坏规则。我对docstring使用三重双引号,对正则表达式使用原始字符串,即使不需要它们。

例如:

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

相关问题 更多 >