我喜欢在用于插值的字符串周围使用双引号或者是自然语言消息,对于类似小符号的字符串使用单引号,但如果字符串包含引号,或者如果我忘记,则会破坏规则.我对正则表达式使用三重双引号用于文档字符串和原始字符串文字,即使它们不需要也是如此.
例如:
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