【问题标题】:Why does Python return an escaping backslash in a string?为什么 Python 在字符串中返回转义反斜杠?
【发布时间】:2016-08-08 06:11:22
【问题描述】:
'\"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?"

【问题讨论】:

    标签: python string syntax escaping


    【解决方案1】:

    因为在第一个中,整个字符串都是单引号,所以应该转义另一个单引号。而在第二个中,整个字符串都用双引号引起来。

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

    【讨论】:

    • 对不起,我不明白:两个字符串都用单引号括起来。如果我不转义双引号之间的单引号,则会出现语法错误。
    • @oaklander114 是的,但是 python 更改了它们以获得更好的表示。就是这样,否则这些用于封装字符串的引号之间没有区别。
    • 我明白了,除了使用打印功能,没有办法避免吗?
    • @oaklander114 是的,我认为根本不需要这样做,仅对于自定义表示,您可以手动使用适当的引号来获得预期的输出,有时是 1、2 甚至 3 引号。
    【解决方案2】:

    转义字符是必需的,因为如果准确输入,该字符会重现该字符串。字符串同时包含单引号和双引号,因此无论哪种类型的字符串都需要在字符串中进行转义。

    【讨论】:

      【解决方案3】:

      您可以选择单引号或双引号将字符串括起来。任何出现的封闭引号字符都必须使用“\”进行转义。

      >>> 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'
      >>>
      

      【讨论】:

      • 当您在字符串中使用两种类型的引号时,会出现奇怪的(至少对我而言)行为。例如 e = "\"Hello\'s\"" 。在这种情况下,转义的反斜杠会显示在输出中。
      • 这很奇怪。起初我认为这是因为字符串是双引号的,但如果你这样做 f="Hello\'s" 你会得到预期的行为,我想知道这是否是一个错误。
      • 这只是 REPL shell 中的显示问题。字符串长度正确,字符位置正确。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-26
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      • 2012-12-24
      • 1970-01-01
      相关资源
      最近更新 更多