在原始字符串 r'...' 中如何转义单引号 (')

14

我希望它能够打印出来

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

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

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

但是它会打印出来

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

在原始字符串中,正确的转义 '(单引号)的方法是什么?

2个回答

15

引用自Python字符串字面量文档

当出现'r''R'前缀时,后面跟随反斜杠的字符将不做任何改变地包含在字符串中,并且所有反斜杠都将保留在字符串中。例如,字符串字面量r"\n"由两个字符组成:一个反斜杠和一个小写的'n'字符串引号可以通过反斜杠进行转义,但是反斜杠仍然会保留在字符串中;例如,r"\""是一个有效的字符串字面量,由两个字符组成:一个反斜杠和一个双引号。

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

  1. Using multiline raw strings, like mentioned in the section Python Strings

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

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

9
>>> a=r'''this is '(single quote) and "(double quote)'''
>>> print(a)
this is '(single quote) and "(double quote)

@william007 这使它成为一个多行字符串,在下一个匹配的三引号之前不会结束。 - jonrsharpe
问题是“在原始字符串中转义'的正确方法是什么”,而不是“如何避免在原始字符串中需要转义'”... - Chris Martin
@ChrisMartin 是的,好的,回答一下 OP 的问题,在这种特定情况下是不可能的。 - jamylak
1
@ChrisMartin 正如我在我的回答中提到的,这是不可能的,但有两种解决这个问题的替代方法。 - thefourtheye

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接