在字符串文字前加“r"有什么作用?意思是? [英] What does preceding a string literal with "r" mean?
问题描述
我第一次看到它用于跨多行构建正则表达式作为 re.compile()
的方法参数,所以我假设 r
代表 RegEx.
I first saw it used in building regular expressions across multiple lines as a method argument to re.compile()
, so I assumed that r
stands for RegEx.
例如:
regex = re.compile(
r'^[A-Z]'
r'[A-Z0-9-]'
r'[A-Z]$', re.IGNORECASE
)
那么在这种情况下 r
是什么意思?为什么我们需要它?
So what does r
mean in this case? Why do we need it?
推荐答案
r
表示字符串将被视为原始字符串,这意味着所有转义码都将被忽略.
The r
means that the string is to be treated as a raw string, which means all escape codes will be ignored.
举个例子:
'
'
将被视为换行符,而 r'
'
将被视为 后面的字符通过
n
.
'
'
will be treated as a newline character, while r'
'
will be treated as the characters followed by
n
.
当存在 'r'
或 'R'
前缀时,反斜杠后面的字符是包含在字符串中而没有更改,并且所有反斜杠都留在细绳.例如,字符串文字 r"
"
由两个字符:反斜杠和小写 'n'
.字符串引号可以是用反斜杠转义,但是反斜杠保留在字符串中;为了例如,r"""
是一个有效的字符串由两个字符组成的字面量:一个反斜杠和一个双引号;r""
不是有效的字符串文字(即使是原始字符串不能以奇数结尾反斜杠).具体来说,一个原始的字符串不能以单个结尾反斜杠(因为反斜杠会转义以下引号字符).另请注意,单个反斜杠后跟换行符被解释作为这两个字符的一部分字符串,而不是作为换行符.
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" "
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;r""
is not a valid string literal (even a raw string cannot end in an odd number of backslashes). Specifically, a raw string cannot end in a single backslash (since the backslash would escape the following quote character). Note also that a single backslash followed by a newline is interpreted as those two characters as part of the string, not as a line continuation.
来源:Python 字符串文字
这篇关于在字符串文字前加“r"有什么作用?意思是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!