【问题标题】:Escape single quote (') in raw string r'...'在原始字符串 r'...' 中转义单引号 (')
【发布时间】:2015-02-12 14:15:45
【问题描述】:

我想打印出来

this is '(single quote) and "(double quote)

我使用以下(我想在这里使用原始字符串'r')

a=r'this is \'(single quote) and "(double quote)' 

但它会打印出来

this is \'(single quote) and "(double quote)

在原始字符串中转义 ' 的正确方法是什么?

【问题讨论】:

    标签: python string python-2.7


    【解决方案1】:

    引用Python String Literals Docs

    当存在'r''R' 前缀时,反斜杠后面的字符将原样包含在字符串中,并且所有反斜杠都保留在字符串中。例如,字符串文字 r"\n" 由两个字符组成:一个反斜杠和一个小写字母 'n'字符串引号可以用反斜杠转义,但反斜杠保留在字符串中;例如,r"\"" 是由两个字符组成的有效字符串文字:反斜杠和双引号。

    有两种方法可以解决这个问题

    1. 使用多行原始字符串,如Python Strings 部分所述

      print(r"""this is '(single quote) and "(double quote)""")
      # this is '(single quote) and "(double quote)
      
    2. 使用String literal concatenation

      print(r"this is '(single quote) and " r'"(double quote)')
      # this is '(single quote) and "(double quote)
      

    【讨论】:

      【解决方案2】:
      >>> a=r'''this is '(single quote) and "(double quote)'''
      >>> print(a)
      this is '(single quote) and "(double quote)
      

      【讨论】:

      • @william007 使它成为一个多行字符串,直到下一个匹配的三引号才结束。
      • 问题是“在原始字符串中转义' 的正确方法是什么”,而不是“如何避免需要在原始字符串中转义'”...跨度>
      • @ChrisMartin True,很好地回答 OP,在这种特定情况下它是不可能的。
      • @ChrisMartin 正如我在my answer 中提到的,这是不可能的,但是对于这个问题有两种替代方案。
      猜你喜欢
      • 1970-01-01
      • 2023-01-24
      • 2020-10-09
      • 2018-08-31
      • 2023-04-02
      • 2012-05-30
      相关资源
      最近更新 更多