Python中的单引号和双引号

时间:2021-12-07 03:46:33

According to the documentation, they're pretty much interchangeable. Is there a stylistic reason to use one over the other?

根据文档,它们几乎是可以互换的。在风格上有什么理由让你选择其中一种呢?

19 个解决方案

#1


525  

I like to use double quotes around strings that are used for interpolation or that are natural language messages, and single quotes for small symbol-like strings, but will break the rules if the strings contain quotes, or if I forget. I use triple double quotes for docstrings and raw string literals for regular expressions even if they aren't needed.

我喜欢用双引号括住用于插值或自然语言消息的字符串,用单引号括住类似符号的小字符串,但如果字符串包含引号,或者我忘记了,就会打破规则。我对docstring使用三重双引号,对正则表达式使用原始字符串常量,即使不需要它们。

For example:

例如:

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

#2


96  

Quoting the official docs at https://docs.python.org/2.0/ref/strings.html:

引用https://docs.python.org/2.0/ref/strings.html的官方文档:

In plain English: String literals can be enclosed in matching single quotes (') or double quotes (").

在普通英语中:字符串文字可以包含在匹配的单引号(')或双引号(")中。

So there is no difference. Instead, people will tell you to choose whichever style that matches the context, and to be consistent. And I would agree - adding that it is pointless to try to come up with "conventions" for this sort of thing because you'll only end up confusing any newcomers.

所以没有区别。相反,人们会告诉你选择任何与上下文匹配的样式,并保持一致。我同意这一点——我补充说,试图为这类事情制定“惯例”是没有意义的,因为你只会让任何新来者感到困惑。

#3


90  

I used to prefer ', especially for '''docstrings''', as I find """this creates some fluff""". Also, ' can be typed without the Shift key on my Swiss German keyboard.

我以前更喜欢',尤其是'docstring ',因为我发现"""这会产生一些绒毛""" ""。此外,我还可以不用瑞士德语键盘上的Shift键打字。

I have since changed to using triple quotes for """docstrings""", to conform to PEP 257.

此后,我改为使用““docstring”“”的三重引号,以符合PEP 257。

#4


44  

I'm with Will:

我将:

  • Double quotes for text
  • 双引号的文本
  • Single quotes for anything that behaves like an identifier
  • 任何行为类似标识符的事物的单引号
  • Double quoted raw string literals for regexps
  • 用于regexp的双引号的原始字符串文字
  • Tripled double quotes for docstrings
  • 对docstring的双引号增加了两倍。

I'll stick with that even if it means a lot of escaping.

我将坚持这一点,即使这意味着要逃避很多。

I get the most value out of single quoted identifiers standing out because of the quotes. The rest of the practices are there just to give those single quoted identifiers some standing room.

我从单引号标识符中获得了最大的值,因为它们是引号。其余的实践只是为了给那些单引号标识符一些站得住脚的空间。

#5


26  

If the string you have contains one, then you should use the other. For example, "You're able to do this", or 'He said "Hi!"'. Other than that, you should simply be as consistent as you can (within a module, within a package, within a project, within an organisation).

如果您拥有的字符串包含一个,那么您应该使用另一个。例如,“你可以这么做”,或者“他说了‘嗨!’”。除此之外,您应该尽可能地保持一致(在一个模块内,在一个包内,在一个项目内,在一个组织内)。

If your code is going to be read by people who work with C/C++ (or if you switch between those languages and Python), then using '' for single-character strings, and "" for longer strings might help ease the transition. (Likewise for following other languages where they are not interchangeable).

如果您的代码将由使用C/ c++的人读取(或者如果您在这些语言和Python之间切换),那么使用“for single-character string”和“for long string”可能有助于简化转换。(同样适用于其他不能互换的语言)。

The Python code I've seen in the wild tends to favour " over ', but only slightly. The one exception is that """these""" are much more common than '''these''', from what I have seen.

我在野生环境中看到的Python代码倾向于“超过”,但只是稍微有点。唯一的例外是“这些”比“这些”要普遍得多。

#6


21  

Triple quoted comments are an interesting subtopic of this question. PEP 257 specifies triple quotes for doc strings. I did a quick check using Google Code Search and found that triple double quotes in Python are about 10x as popular as triple single quotes -- 1.3M vs 131K occurrences in the code Google indexes. So in the multi line case your code is probably going to be more familiar to people if it uses triple double quotes.

三重引用的注释是这个问题的一个有趣的子主题。PEP 257指定doc字符串的三重引号。我使用谷歌代码搜索进行了快速检查,发现Python中的三重双引号的流行程度是三重单引号的10倍,即代码谷歌索引中的1.3M对131K个引号。在多行情况下,如果使用三重双引号,代码可能会更熟悉。

#7


13  

"If you're going to use apostrophes, 
       ^

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

For that simple reason, I always use double quotes on the outside. Always

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

Speaking of fluff, what good is streamlining your string literals with ' if you're going to have to use escape characters to represent apostrophes? Does it offend coders to read novels? I can't imagine how painful high school English class was for you!

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

#8


7  

Python uses quotes something like this:

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

Which gives the following output:

它给出如下输出:

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'

#9


3  

I use double quotes in general, but not for any specific reason - Probably just out of habit from Java.

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

I guess you're also more likely to want apostrophes in an inline literal string than you are to want double quotes.

我猜你更可能想要在内联文字字符串中使用撇号,而不是双引号。

#10


3  

Personally I stick with one or the other. It doesn't matter. And providing your own meaning to either quote is just to confuse other people when you collaborate.

就我个人而言,我坚持其中之一。没关系。提供你自己的意思在任何引用只是迷惑其他人当你合作。

#11


2  

It's probably a stylistic preference more than anything. I just checked PEP 8 and didn't see any mention of single versus double quotes.

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

I prefer single quotes because its only one keystroke instead of two. That is, I don't have to mash the shift key to make single quote.

我喜欢单引号,因为它只有一个按键而不是两个。也就是说,我不需要把shift键合为单引号。

#12


2  

In Perl you want to use single quotes when you have a string which doesn't need to interpolate variables or escaped characters like \n, \t, \r, etc.

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

PHP makes the same distinction as Perl: content in single quotes will not be interpreted (not even \n will be converted), as opposed to double quotes which can contain variables to have their value printed out.

PHP与Perl有相同的区别:单引号中的内容不会被解释(甚至连\n都不会被转换),而双引号可以包含要打印值的变量。

Python does not, I'm afraid. Technically seen, there is no $ token (or the like) to separate a name/text from a variable in Python. Both features make Python more readable, less confusing, after all. Single and double quotes can be used interchangeably in Python.

Python恐怕不行。从技术上看,在Python中没有$ token(或类似的东西)来从变量中分离名称/文本。这两个特性都使Python更易于阅读,也更不容易混淆。单引号和双引号可以在Python中交替使用。

#13


1  

I chose to use double quotes because they are easier to see.

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

#14


1  

I just use whatever strikes my fancy at the time; it's convenient to be able to switch between the two at a whim!

我只是用当时我喜欢的东西;在这两者之间切换很方便。

Of course, when quoting quote characetrs, switching between the two might not be so whimsical after all...

当然,当引用了这些人物的台词时,在两者之间切换可能不会那么异想天开……

#15


0  

Your team's taste or your project's coding guidelines.

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

If you are in a multilanguage environment, you might wish to encourage the use of the same type of quotes for strings that the other language uses, for instance. Else, I personally like best the look of '

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

#16


0  

None as far as I know. Although if you look at some code, " " is commonly used for strings of text (I guess ' is more common inside text than "), and ' ' appears in hashkeys and things like that.

据我所知没有。虽然如果你看一些代码,“”通常用于文本字符串(我猜“在文本中比”更常见),“”出现在hashkeys中等等。

#17


0  

I aim to minimize both pixels and surprise. I typically prefer ' in order to minimize pixels, but " instead if the string has an apostrophe, again to minimize pixels. For a docstring, however, I prefer """ over ''' because the latter is non-standard, uncommon, and therefore surprising. If now I have a bunch of strings where I used " per the above logic, but also one that can get away with a ', I may still use " in it to preserve consistency, only to minimize surprise.

我的目标是最小化像素和惊喜。我通常更喜欢“为了最小化像素,但是”如果字符串有撇号,还是要最小化像素。然而,对于docstring,我更喜欢“”而不是“”,因为后者是非标准的、不常见的,因此令人惊讶。如果现在我有一串字符串,其中我使用了“根据上面的逻辑,但也可以使用',我仍然可以使用”来保持一致性,只是为了减少意外。

Perhaps it helps to think of the pixel minimization philosophy in the following way. Would you rather that English characters looked like A B C or AA BB CC? The latter choice wastes 50% of the non-empty pixels.

也许用以下的方法来考虑像素最小化的原理是有帮助的。你希望英文字符看起来像B C还是AA BB CC?后者浪费了50%的非空像素。

#18


-1  

I use double quotes because I have been doing so for years in most languages (C++, Java, VB…) except Bash, because I also use double quotes in normal text and because I'm using a (modified) non-English keyboard where both characters require the shift key.

我使用双引号是因为我已经在大多数语言(c++、Java、VB…)中使用了多年,除了Bash,因为我还在普通文本中使用双引号,因为我使用了一个(修改过的)非英语键盘,两个字符都需要shift键。

#19


-4  

' = "

“=”

/ = \ = \\

\ = \ = \

example :

例子:

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

Results are the same

结果都是一样的

=>> no, they're not the same. A single backslash will escape characters. You just happen to luck out in that example because \k and \w aren't valid escapes like \t or \n or \\ or \"

=>>不,它们不一样。一个反斜杠将转义字符。在这个例子中你只是碰巧遇到了运气,因为\k和\w不是像\t或\n或\或\或\

If you want to use single backslashes (and have them interpreted as such), then you need to use a "raw" string. You can do this by putting an 'r' in front of the string

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

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

As far as paths in Windows are concerned, forward slashes are interpreted the same way. Clearly the string itself is different though. I wouldn't guarantee that they're handled this way on an external device though.

就窗口中的路径而言,前斜杠的解释方式相同。显然弦本身是不同的。我不能保证它们在外部设备上是这样处理的。

#1


525  

I like to use double quotes around strings that are used for interpolation or that are natural language messages, and single quotes for small symbol-like strings, but will break the rules if the strings contain quotes, or if I forget. I use triple double quotes for docstrings and raw string literals for regular expressions even if they aren't needed.

我喜欢用双引号括住用于插值或自然语言消息的字符串,用单引号括住类似符号的小字符串,但如果字符串包含引号,或者我忘记了,就会打破规则。我对docstring使用三重双引号,对正则表达式使用原始字符串常量,即使不需要它们。

For example:

例如:

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

#2


96  

Quoting the official docs at https://docs.python.org/2.0/ref/strings.html:

引用https://docs.python.org/2.0/ref/strings.html的官方文档:

In plain English: String literals can be enclosed in matching single quotes (') or double quotes (").

在普通英语中:字符串文字可以包含在匹配的单引号(')或双引号(")中。

So there is no difference. Instead, people will tell you to choose whichever style that matches the context, and to be consistent. And I would agree - adding that it is pointless to try to come up with "conventions" for this sort of thing because you'll only end up confusing any newcomers.

所以没有区别。相反,人们会告诉你选择任何与上下文匹配的样式,并保持一致。我同意这一点——我补充说,试图为这类事情制定“惯例”是没有意义的,因为你只会让任何新来者感到困惑。

#3


90  

I used to prefer ', especially for '''docstrings''', as I find """this creates some fluff""". Also, ' can be typed without the Shift key on my Swiss German keyboard.

我以前更喜欢',尤其是'docstring ',因为我发现"""这会产生一些绒毛""" ""。此外,我还可以不用瑞士德语键盘上的Shift键打字。

I have since changed to using triple quotes for """docstrings""", to conform to PEP 257.

此后,我改为使用““docstring”“”的三重引号,以符合PEP 257。

#4


44  

I'm with Will:

我将:

  • Double quotes for text
  • 双引号的文本
  • Single quotes for anything that behaves like an identifier
  • 任何行为类似标识符的事物的单引号
  • Double quoted raw string literals for regexps
  • 用于regexp的双引号的原始字符串文字
  • Tripled double quotes for docstrings
  • 对docstring的双引号增加了两倍。

I'll stick with that even if it means a lot of escaping.

我将坚持这一点,即使这意味着要逃避很多。

I get the most value out of single quoted identifiers standing out because of the quotes. The rest of the practices are there just to give those single quoted identifiers some standing room.

我从单引号标识符中获得了最大的值,因为它们是引号。其余的实践只是为了给那些单引号标识符一些站得住脚的空间。

#5


26  

If the string you have contains one, then you should use the other. For example, "You're able to do this", or 'He said "Hi!"'. Other than that, you should simply be as consistent as you can (within a module, within a package, within a project, within an organisation).

如果您拥有的字符串包含一个,那么您应该使用另一个。例如,“你可以这么做”,或者“他说了‘嗨!’”。除此之外,您应该尽可能地保持一致(在一个模块内,在一个包内,在一个项目内,在一个组织内)。

If your code is going to be read by people who work with C/C++ (or if you switch between those languages and Python), then using '' for single-character strings, and "" for longer strings might help ease the transition. (Likewise for following other languages where they are not interchangeable).

如果您的代码将由使用C/ c++的人读取(或者如果您在这些语言和Python之间切换),那么使用“for single-character string”和“for long string”可能有助于简化转换。(同样适用于其他不能互换的语言)。

The Python code I've seen in the wild tends to favour " over ', but only slightly. The one exception is that """these""" are much more common than '''these''', from what I have seen.

我在野生环境中看到的Python代码倾向于“超过”,但只是稍微有点。唯一的例外是“这些”比“这些”要普遍得多。

#6


21  

Triple quoted comments are an interesting subtopic of this question. PEP 257 specifies triple quotes for doc strings. I did a quick check using Google Code Search and found that triple double quotes in Python are about 10x as popular as triple single quotes -- 1.3M vs 131K occurrences in the code Google indexes. So in the multi line case your code is probably going to be more familiar to people if it uses triple double quotes.

三重引用的注释是这个问题的一个有趣的子主题。PEP 257指定doc字符串的三重引号。我使用谷歌代码搜索进行了快速检查,发现Python中的三重双引号的流行程度是三重单引号的10倍,即代码谷歌索引中的1.3M对131K个引号。在多行情况下,如果使用三重双引号,代码可能会更熟悉。

#7


13  

"If you're going to use apostrophes, 
       ^

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

For that simple reason, I always use double quotes on the outside. Always

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

Speaking of fluff, what good is streamlining your string literals with ' if you're going to have to use escape characters to represent apostrophes? Does it offend coders to read novels? I can't imagine how painful high school English class was for you!

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

#8


7  

Python uses quotes something like this:

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

Which gives the following output:

它给出如下输出:

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'

#9


3  

I use double quotes in general, but not for any specific reason - Probably just out of habit from Java.

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

I guess you're also more likely to want apostrophes in an inline literal string than you are to want double quotes.

我猜你更可能想要在内联文字字符串中使用撇号,而不是双引号。

#10


3  

Personally I stick with one or the other. It doesn't matter. And providing your own meaning to either quote is just to confuse other people when you collaborate.

就我个人而言,我坚持其中之一。没关系。提供你自己的意思在任何引用只是迷惑其他人当你合作。

#11


2  

It's probably a stylistic preference more than anything. I just checked PEP 8 and didn't see any mention of single versus double quotes.

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

I prefer single quotes because its only one keystroke instead of two. That is, I don't have to mash the shift key to make single quote.

我喜欢单引号,因为它只有一个按键而不是两个。也就是说,我不需要把shift键合为单引号。

#12


2  

In Perl you want to use single quotes when you have a string which doesn't need to interpolate variables or escaped characters like \n, \t, \r, etc.

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

PHP makes the same distinction as Perl: content in single quotes will not be interpreted (not even \n will be converted), as opposed to double quotes which can contain variables to have their value printed out.

PHP与Perl有相同的区别:单引号中的内容不会被解释(甚至连\n都不会被转换),而双引号可以包含要打印值的变量。

Python does not, I'm afraid. Technically seen, there is no $ token (or the like) to separate a name/text from a variable in Python. Both features make Python more readable, less confusing, after all. Single and double quotes can be used interchangeably in Python.

Python恐怕不行。从技术上看,在Python中没有$ token(或类似的东西)来从变量中分离名称/文本。这两个特性都使Python更易于阅读,也更不容易混淆。单引号和双引号可以在Python中交替使用。

#13


1  

I chose to use double quotes because they are easier to see.

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

#14


1  

I just use whatever strikes my fancy at the time; it's convenient to be able to switch between the two at a whim!

我只是用当时我喜欢的东西;在这两者之间切换很方便。

Of course, when quoting quote characetrs, switching between the two might not be so whimsical after all...

当然,当引用了这些人物的台词时,在两者之间切换可能不会那么异想天开……

#15


0  

Your team's taste or your project's coding guidelines.

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

If you are in a multilanguage environment, you might wish to encourage the use of the same type of quotes for strings that the other language uses, for instance. Else, I personally like best the look of '

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

#16


0  

None as far as I know. Although if you look at some code, " " is commonly used for strings of text (I guess ' is more common inside text than "), and ' ' appears in hashkeys and things like that.

据我所知没有。虽然如果你看一些代码,“”通常用于文本字符串(我猜“在文本中比”更常见),“”出现在hashkeys中等等。

#17


0  

I aim to minimize both pixels and surprise. I typically prefer ' in order to minimize pixels, but " instead if the string has an apostrophe, again to minimize pixels. For a docstring, however, I prefer """ over ''' because the latter is non-standard, uncommon, and therefore surprising. If now I have a bunch of strings where I used " per the above logic, but also one that can get away with a ', I may still use " in it to preserve consistency, only to minimize surprise.

我的目标是最小化像素和惊喜。我通常更喜欢“为了最小化像素,但是”如果字符串有撇号,还是要最小化像素。然而,对于docstring,我更喜欢“”而不是“”,因为后者是非标准的、不常见的,因此令人惊讶。如果现在我有一串字符串,其中我使用了“根据上面的逻辑,但也可以使用',我仍然可以使用”来保持一致性,只是为了减少意外。

Perhaps it helps to think of the pixel minimization philosophy in the following way. Would you rather that English characters looked like A B C or AA BB CC? The latter choice wastes 50% of the non-empty pixels.

也许用以下的方法来考虑像素最小化的原理是有帮助的。你希望英文字符看起来像B C还是AA BB CC?后者浪费了50%的非空像素。

#18


-1  

I use double quotes because I have been doing so for years in most languages (C++, Java, VB…) except Bash, because I also use double quotes in normal text and because I'm using a (modified) non-English keyboard where both characters require the shift key.

我使用双引号是因为我已经在大多数语言(c++、Java、VB…)中使用了多年,除了Bash,因为我还在普通文本中使用双引号,因为我使用了一个(修改过的)非英语键盘,两个字符都需要shift键。

#19


-4  

' = "

“=”

/ = \ = \\

\ = \ = \

example :

例子:

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

Results are the same

结果都是一样的

=>> no, they're not the same. A single backslash will escape characters. You just happen to luck out in that example because \k and \w aren't valid escapes like \t or \n or \\ or \"

=>>不,它们不一样。一个反斜杠将转义字符。在这个例子中你只是碰巧遇到了运气,因为\k和\w不是像\t或\n或\或\或\

If you want to use single backslashes (and have them interpreted as such), then you need to use a "raw" string. You can do this by putting an 'r' in front of the string

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

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

As far as paths in Windows are concerned, forward slashes are interpreted the same way. Clearly the string itself is different though. I wouldn't guarantee that they're handled this way on an external device though.

就窗口中的路径而言,前斜杠的解释方式相同。显然弦本身是不同的。我不能保证它们在外部设备上是这样处理的。