在原始字符串 r'...' 中转义单引号 (') [英] Escape single quote (') in raw string r'...'
问题描述
我想打印出来
this is '(single quote) and "(double quote)
我使用以下(我想在这里使用原始字符串 'r')
I use the following (I want to use raw string 'r' here)
a=r'this is \'(single quote) and "(double quote)'
但它打印出来
this is \'(single quote) and "(double quote)
在原始字符串中转义 ' 的正确方法是什么?
What is the correct way to escape ' in raw string?
推荐答案
引用自 Python 字符串文字文档、
当存在 'r'
或 'R'
前缀时,反斜杠后面的字符不加更改地包含在字符串中,并且所有反斜杠都保留在字符串中细绳.例如,字符串文字 r"\n"
由两个字符组成:一个反斜杠和一个小写的 'n'
.字符串引号可以用反斜杠转义,但反斜杠保留在字符串中;例如,r"\""
是一个由两个字符组成的有效字符串文字:a反斜杠和双引号.
When an
'r'
or'R'
prefix is present, a character following a backslash is included in the string without change, and all backslashes are left in the string. For example, the string literalr"\n"
consists of two characters: a backslash and a lowercase'n'
. String quotes can be escaped with a backslash, but the backslash remains in the string; for example,r"\""
is a valid string literal consisting of two characters: a backslash and a double quote.
有两种方法可以解决这个问题
There are two ways to fixing this
使用多行原始字符串,如Python 字符串
print(r"""this is '(single quote) and "(double quote)""")
# this is '(single quote) and "(double quote)
使用字符串文字串联,
print(r"this is '(single quote) and " r'"(double quote)')
# this is '(single quote) and "(double quote)
这篇关于在原始字符串 r'...' 中转义单引号 (')的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!