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