在python中的字符串之前'r'代表什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33729045/
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-19 13:51:36  来源:igfitidea点击:

What does an 'r' represent before a string in python?

pythonpython-2.7

提问by Rahul

I want to understand why do we use a r before a path name in python such as

我想了解为什么我们在 python 中的路径名之前使用 ar,例如

dirname = r'C:\temp\parts'

回答by Rahul Tripathi

r means the string will be treated as raw string.

r 表示字符串将被视为原始字符串。

From here:

这里

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' 或 'R' 前缀时,反斜杠后面的字符将包含在字符串中而不会更改,并且所有反斜杠都保留在字符串中。例如,字符串文字 r"\n" 由两个字符组成:一个反斜杠和一个小写的 'n'。字符串引号可以用反斜杠转义,但反斜杠保留在字符串中;例如,r"\"" 是由两个字符组成的有效字符串文字:反斜杠和双引号;r"\" 不是有效的字符串文字(即使原始字符串也不能以奇数个反斜杠结尾)。具体来说,原始字符串不能以单个反斜杠结尾(因为反斜杠会转义后面的引号字符)。