python - 在字符串文字前面加上 "r"是什么意思?

标签 python string syntax literals rawstring

我第一次看到它用于构建多行正则表达式作为 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 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

关于python - 在字符串文字前面加上 "r"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4780088/

相关文章:

python - 如何写入文本文件中每一行的开头和结尾?

haskell - 运行程序时出错

Python - 类型错误 : unbound method

python - 用于热图的 pandas 数据透视表

Python 递归双字母

python - 将带双引号的字符串拆分为列表

c# - 如何使用 vb.net/C# 以自定义格式获取星期名称

string - 在Powershell中从字符串中提取字符串

sql - 用于从特定行生成列的大查询语法

git - 这些 `git fetch` 语法有什么区别?