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


当前回答

我通常使用双引号,但不是为了任何特定的原因——可能只是出于Java的习惯。

我猜在内联文字字符串中,您更可能需要撇号而不是双引号。

其他回答

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

例如:

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

' = "

/ = \ = \\

例子:

f = open('c:\word.txt', 'r')
f = open("c:\word.txt", "r")
f = open("c:/word.txt", "r")
f = open("c:\\\word.txt", "r")

结果是一样的

>>不,它们不一样。 一个反斜杠将转义字符。在这个例子中,你只是碰巧走运,因为\k和\w不是有效的转义,就像\t或\n或\\或\"

如果你想使用单个反斜杠(并将它们解释为反斜杠),那么你需要使用一个“原始”字符串。你可以在字符串前面加上一个'r'来做到这一点

im_raw = r'c:\temp.txt'
non_raw = 'c:\\temp.txt'
another_way = 'c:/temp.txt'

就Windows中的路径而言,正斜杠的解释是相同的。显然字符串本身是不同的。但我不能保证它们在外部设备上也能以这种方式处理。

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

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

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

就我个人而言,我坚持两者之一。没关系。当你们合作的时候,为这两句话提供自己的意思只会让其他人感到困惑。

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'