根据文档,它们几乎是可以互换的。是否有使用其中一种而不是另一种的风格原因?


当前回答

在Perl中,当您有一个不需要插入变量或转义字符(如\n, \t, \r等)的字符串时,您希望使用单引号。

PHP与Perl做了相同的区分:单引号中的内容不会被解释(甚至\n也不会被转换),而双引号中可以包含变量并将其值打印出来。

恐怕Python没有。从技术上看,Python中没有$令牌(或类似的)将名称/文本与变量分开。毕竟,这两个特性都使Python更具可读性,不那么令人困惑。在Python中,单引号和双引号可以互换使用。

其他回答

这可能是一种风格上的偏好。我刚刚检查了PEP 8,没有看到任何提到单引号和双引号。

我更喜欢单引号,因为它只有一个按键,而不是两个。也就是说,我不需要捣碎shift键来做单引号。

我的目标是最小化像素和惊喜。我通常更喜欢' in order to最小化像素,但是' '如果字符串有撇号,同样是为了最小化像素。然而,对于文档字符串,我更喜欢"""而不是" ',因为后者是不标准的、不常见的,因此令人惊讶。如果现在我有一堆字符串,我使用“根据上面的逻辑,但也可以使用一个',我可能仍然使用”,以保持一致性,只是为了尽量减少惊喜。

也许用以下方式来思考像素最小化哲学会有所帮助。你更希望英文字符看起来像A B C还是AA BB CC?后一种选择浪费了50%的非空像素。

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

例如:

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

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'

您的团队的品味或项目的编码指南。

例如,如果您处于多语言环境中,您可能希望鼓励对字符串使用与其他语言相同类型的引号。除此之外,我个人最喜欢的是