gpt4 book ai didi

python - re 模块 - r 符号是什么?

转载 作者:太空狗 更新时间:2023-10-30 02:34:30 26 4
gpt4 key购买 nike

我试着理解这段代码:

Var1 = re.compile(r"nothing is (\d+)").search

我想看看\d 上 ( 符号之后的 r 符号有什么影响。我知道\d 表示查找小数(\表示 d 具有特殊含义),这是否意味着没有 r 符号我会使用\?如果是为什么?我知道在 bash shell 中只放一个\就足够了。

我在这里阅读:http://docs.python.org/library/re.html#raw-string-notation

但我不明白它如何影响上面的代码片段。谢谢。

最佳答案

这是一个raw string literal .它改变了反斜杠以按字面意义对待(几乎,见下文)。这在编写正则表达式时特别有用,因为它们通常包含反斜杠,如果您使用普通字符串文字,则可能必须转义反斜杠,从而使正则表达式更难阅读。

如果没有 r,您的代码将如下所示:

f = re.compile("nothing is (\\d+)").search

请注意,在这种情况下不转义反斜杠也有效,因为 '\d' 不是有效的转义序列:

f = re.compile("nothing is (\d+)").search

但是,除非您(以及必须维护您的代码的每个人)能够记住允许的转义序列列表,否则依赖此行为可能会导致错误。


原始字符串文字的规则是:

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 - re 模块 - r 符号是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8023392/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com