在字符串文字前加"r"会做什么?意思是? [英] What does preceding a string literal with "r" mean?

查看:182
本文介绍了在字符串文字前加"r"会做什么?意思是?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我首先看到它用于跨多行构建正则表达式,作为re.compile()的方法参数,因此我假设r代表RegEx.

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

例如:

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

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

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

推荐答案

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

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

例如:

'\n'将被视为换行符,而r'\n'将被视为字符\后跟n.

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

如果存在'r''R'前缀, 反斜杠后面的字符是 包含在字符串中,无需更改, 并且所有反斜杠都留在了 细绳.例如,字符串 文字r"\n"由两个组成 字符:反斜杠和 小写'n'.字符串引号可以是 以反斜杠逃脱了,但是 反斜杠保留在字符串中;为了 例如,r"\""是有效的字符串 由两个字符组成的文字: 反斜杠和双引号; r"\" 不是有效的字符串文字(即使是 原始字符串不能以奇数结尾 的反斜杠).具体来说,原始 字符串不能以单个结尾 反斜杠(因为反斜杠会 转义以下引号). 另请注意,单个反斜杠 后面跟换行符 作为这两个字符的一部分 字符串,而不是连续行.

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字符串文字

这篇关于在字符串文字前加"r"会做什么?意思是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆