问题:Python中的单引号与双引号[关闭]

根据文档,它们几乎可以互换。是否有出于某种风格的原因要在一个之上使用另一个?

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


回答 0

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

例如:

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

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.

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

回答 1

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

用简单的英语:字符串文字可以用匹配的单引号(’)或双引号(“)括起来。

因此没有区别。取而代之的是,人们会告诉您选择与上下文匹配并且一致的样式。我会同意-补充一点,试图为此类事情提出“惯例”是没有意义的,因为这样只会使任何新来者感到困惑。

Quoting the official docs at 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.


回答 2

我以前喜欢',尤其是对'''docstrings''',因为我觉得"""this creates some fluff"""。另外,'无需Shift我的瑞士德语键盘上的键即可键入。

从那以后,我改变为使用三引号"""docstrings""",以符合PEP 257

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.

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


回答 3

我与Will在一起:

  • 文字双引号
  • 行为类似于标识符的单引号
  • 正则表达式的双引号原始字符串文字
  • 文档字符串三重双引号

我会坚持下去,即使这意味着很多逃避。

从引号引起来的单引号标识符中,我获得了最大的价值。其余的做法只是为了给那些单引号标识符留出一定的空间。

I’m with Will:

  • Double quotes for text
  • Single quotes for anything that behaves like an identifier
  • Double quoted raw string literals for regexps
  • Tripled double quotes for docstrings

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.


回答 4

如果您的字符串包含一个,则应使用另一个。例如"You're able to do this",或'He said "Hi!"'。除此之外,您应该尽可能地保持一致(在模块内,包内,项目内,组织内)。

如果您的代码将由使用C / C ++的人员阅读(或者如果您在这些语言和Python之间切换),则将其''用于单字符字符串和""较长的字符串可能有助于简化转换。(同样地,对于遵循其他不可互换的其他语言)。

我在野外看到的Python代码倾向于优先"',但只是略微偏偏。从我所看到的情况来看,一个exceptions是,"""these"""它比普遍得多'''these'''

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).

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.


回答 5

用三引号引起来的注释是该问题的一个有趣的子主题。PEP 257指定文档字符串的三引号。我使用Google代码搜索进行了快速检查,发现Python中的三重双引号大约是三重单引号的 10倍-在Google索引的代码中出现了130万对131K。因此,在多行情况下,如果使用三重双引号,您的代码可能会变得更加熟悉。

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.


回答 6

"If you're going to use apostrophes, 
       ^

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

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

说到绒毛,如果您将不得不使用转义字符来表示撇号,那么用’简化字符串文字有什么好处?它会冒犯编码员阅读小说吗?我无法想象高中英语课对你有多痛苦!

"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!


回答 7

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'

Python uses quotes something like this:

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'

回答 8

我通常使用双引号,但出于某种原因而不是使用双引号-可能只是出于Java的习惯。

我猜您也更希望内联文字字符串中使用撇号,而不是双引号。

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

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


回答 9

我个人坚持一个或另一个。没关系 提供您自己的意思来引用任何一种,只是在您进行协作时使其他人感到困惑。

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.


回答 10

风格上的偏爱可能比什么都重要。我只是检查了PEP 8,却没有提到单引号和双引号。

我更喜欢单引号,因为它只有一个击键而不是两个击键。也就是说,我不必混入Shift键即可制作单引号。

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.

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.


回答 11

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

PHP与Perl的区别是相同的:单引号中的内容将不会被解释(甚至不会转换\ n),而双引号中可能包含变量以显示其值。

恐怕Python没有。从技术上看,在Python中没有$令牌(或类似符号)可将名称/文本与变量分开。毕竟,这两个功能使Python更具可读性,减少了混乱。单引号和双引号可以在Python中互换使用。

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.

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.

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.


回答 12

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

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


回答 13

我只是用当时我喜欢的任何东西;能够一时之间在两者之间切换很方便!

当然,引用报价字符时,毕竟在两者之间切换可能不是那么古怪……

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…


回答 14

您的团队的品味或项目的编码准则。

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

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 ‘


回答 15

据我所知没有。尽管如果看一些代码,“”通常用于文本字符串(我猜想’在文本内部比’更为常见),并且”出现在哈希键之类的东西中。

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.


回答 16

我的目标是尽量减少像素和惊喜。我通常更喜欢'最小化像素,但是"如果字符串中带有单引号,则我还是希望最小化像素。但是,对于文档字符串,我更喜欢"""'''因为后者是非标准的,不常见的,因此令人惊讶。如果现在我"按照上述逻辑使用了一堆字符串,但又可以避免使用a字符串,那么我'仍然可以"在其中使用它来保持一致性,以最大程度地减少意外。

也许可以通过以下方式来考虑像素最小化原理。您希望英文字符看起来像A B C还是AA BB CC?后一种选择浪费了50%的非空像素。

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.

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.


回答 17

我使用双引号,是因为除Bash之外,大多数语言(C ++,Java,VB等)都已经使用多年了,因为我也在普通文本中使用双引号,并且因为我在使用(修改过的)非英语键盘,这两个字符都需要使用Shift键。

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.


回答 18

' = "

/= \=\\

例如:

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不是有效的转义字符,例如\tor \n\\or\"

如果要使用单个反斜杠(并且将反斜杠解释为反斜杠),则需要使用“原始”字符串。您可以通过r在字符串前面加上“ ”来实现

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

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

' = "

/ = \ = \\

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 \"

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

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.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。