Python 字符串文字前面带有“r”是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4780088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 17:29:17  来源:igfitidea点击:

What does preceding a string literal with "r" mean?

pythonstringsyntaxliteralsrawstring

提问by Nikki Erwin Ramirez

I first saw it used in building regular expressions across multiple lines as a method argument to re.compile(), so I assumed that rstands for RegEx.

我第一次看到它用于跨多行构建正则表达式作为 的方法参数re.compile(),所以我认为它r代表 RegEx。

For example:

例如:

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

So what does rmean in this case? Why do we need it?

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

采纳答案by Sebastian Paaske T?rholm

The rmeans that the string is to be treated as a raw string, which means all escape codes will be ignored.

r意味着该字符串将被视为原始字符串,这意味着所有转义码都将被忽略。

For an example:

例如:

'\n'will be treated as a newline character, while r'\n'will be treated as the characters \followed by n.

'\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.

当存在'r'or'R'前缀时,反斜杠后面的字符将不加更改地包含在字符串中,并且所有反斜杠都保留在字符串中。例如,字符串文字r"\n"由两个字符组成:一个反斜杠和一个小写'n'。字符串引号可以用反斜杠转义,但反斜杠保留在字符串中;例如,r"\""是由两个字符组成的有效字符串文字:一个反斜杠和一个双引号;r"\"不是有效的字符串文字(即使是原始字符串也不能以奇数个反斜杠结尾)。具体来说,原始字符串不能以单个反斜杠结尾(因为反斜杠会转义后面的引号字符)。另请注意,单个反斜杠后跟换行符被解释为这两个字符作为字符串的一部分,而不是作为行的延续。

Source: Python string literals

来源:Python 字符串文字

回答by Nate

It means that escapes won't be translated. For example:

这意味着转义不会被翻译。例如:

r'\n'

is a string with a backslash followed by the letter n. (Without the rit would be a newline.)

是一个带有反斜杠后跟字母的字符串n。(没有r它,它将是一个换行符。)

bdoes stand for byte-string and is used in Python 3, where strings are Unicode by default. In Python 2.x strings were byte-strings by default and you'd use uto indicate Unicode.

b确实代表字节字符串,并在 Python 3 中使用,其中字符串默认为 Unicode。在 Python 2.x 中,默认情况下字符串是字节字符串,您可以u用来表示 Unicode。