我希望它能够打印出来
this is '(single quote) and "(double quote)
我使用以下代码(我想在这里使用原始字符串'r'):
a=r'this is \'(single quote) and "(double quote)'
但是它会打印出来
this is \'(single quote) and "(double quote)
在原始字符串中,正确的转义 '(单引号)的方法是什么?
我希望它能够打印出来
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字符串字面量文档,
当出现
'r'
或'R'
前缀时,后面跟随反斜杠的字符将不做任何改变地包含在字符串中,并且所有反斜杠都将保留在字符串中。例如,字符串字面量r"\n"
由两个字符组成:一个反斜杠和一个小写的'n'
。字符串引号可以通过反斜杠进行转义,但是反斜杠仍然会保留在字符串中;例如,r"\""
是一个有效的字符串字面量,由两个字符组成:一个反斜杠和一个双引号。
有两种方法可以解决这个问题
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)
Using String literal concatenation,
print(r"this is '(single quote) and " r'"(double quote)')
# this is '(single quote) and "(double quote)
>>> a=r'''this is '(single quote) and "(double quote)'''
>>> print(a)
this is '(single quote) and "(double quote)