简体   繁体   English

Python为什么要在字符串中返回转义的反斜杠?

[英]Why does Python return an escaping backslash in a string?

'\"atg is a codon, isn\'t it?\" \"Yes, it is\", he answered'

gives as output: 给出作为输出:

'"atg is a codon, isn\'t it?" "Yes, it is", he answered'

Why is the escape character showing up in the output? 为什么转义字符显示在输出中?

When I type the string below, this doesn't happen. 当我在下面键入字符串时,这不会发生。

'This is a codon, isn\'t it?'

The output I get is this: 我得到的输出是这样的:

"This is a codon, isn't it?"

because in first one the whole string is in one-quote so another one-quotes should be escaped. 因为在第一个字符串中,整个字符串都用单引号引起来,所以应将另一个单引号转义。 Whereas in second one the whole string is in double quote. 而在第二个中,整个字符串用双引号引起来。

>>> '\"atg is a codon, isn\'t it?\" \"Yes, it is\", he answered'
'"atg is a codon, isn\'t it?" "Yes, it is", he answered'
^                                                      ^
>>> 
>>> 'This is a codon, isn\'t it?'
"This is a codon, isn't it?"  # there is no need to escape the one-quote between double-quotes         
^                          ^

The escape character is needed because that is the string that, if typed out exactly, would reproduce the string. 需要转义字符,因为如果准确键入该字符串,它将重新生成该字符串。 The string contains both single and double quotes, so whichever type encloses the string will need to be escaped within the string. 该字符串包含单引号和双引号,因此无论哪种类型将字符串括起来,都需要在字符串内进行转义。

You get to choose either single quotes or double quotes to enclose a string. 您可以选择单引号或双引号将字符串括起来。 Any occurrences of your enclosing quote character must be escaped with a '\\'. 出现的引号中任何出现的字符都必须用'\\'进行转义。

>>> b = 'Hello\'s'
>>> a = "Hello's"
>>> b = 'Hello\'s'
>>> c = 'Hello"s'
>>> d = "Hello\"s"
>>> a
"Hello's"
>>> b
"Hello's"
>>> c
'Hello"s'
>>> d
'Hello"s'
>>>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM