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


当前回答

"If you're going to use apostrophes, 
       ^

you'll definitely want to use double quotes".
   ^

出于这个简单的原因,我总是在外面使用双引号。总是

说到无用,如果你必须使用转义字符来表示撇号,那么用'简化字符串文字有什么好处呢?读小说会冒犯程序员吗?我无法想象高中英语课对你来说有多痛苦!

其他回答

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'

我支持威尔:

文本的双引号 任何行为类似于标识符的东西都可以使用单引号 regexp的双引号原始字符串字面量 文档字符串的三倍双引号

即使这意味着要逃跑,我也会坚持下去。

我从单引号标识符中获得了最大的价值。其余的实践只是为了给那些单引号标识符留出一些空间。

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

例如:

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

我选择使用双引号,因为它们更容易看到。

我只是用我当时喜欢的东西;这很方便,能够在两者之间切换心血来潮!

当然,在引用引用字符时,在两者之间切换可能并不是那么异想天开……