我第一次看到它用于构建多行正则表达式作为 re.compile()
的方法参数,所以我假设 r
代表 RegEx。
例如:
regex = re.compile(
r'^[A-Z]'
r'[A-Z0-9-]'
r'[A-Z]$', re.IGNORECASE
)
那么 r
在这种情况下是什么意思呢?为什么我们需要它?
最佳答案
r
表示字符串将被视为原始字符串,这意味着所有转义码都将被忽略。
举个例子:
'\n'
将被视为换行符,而 r'\n'
将被视为后面的字符 \
由 n
.
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;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"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4780088/