在字符串文字前面加上“r”意味着什么?

2024-03-29 13:51:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我第一次看到它在跨多行构建正则表达式时用作re.compile()的方法参数,因此我假设r代表RegEx

例如:

regex = re.compile(
    r'^[A-Z]'
    r'[A-Z0-9-]'
    r'[A-Z]$', re.IGNORECASE
)

那么r在这种情况下是什么意思呢?我们为什么需要它


Tags: 方法re参数情况代表regexcompilez0
2条回答

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 literal r"\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 string literals

这意味着逃避不会被翻译。例如:

r'\n'

是一个带反斜杠的字符串,后跟字母n。(如果没有r,这将是一条新线。)

b代表字节字符串,在Python3中使用,默认情况下字符串为Unicode。在Python2.x中,默认情况下字符串是字节字符串,您可以使用u来表示Unicode

相关问题 更多 >