Python 弃用警告:无效的转义序列 - 用什么代替 \d?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50504500/
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
DeprecationWarning: invalid escape sequence - what to use instead of \d?
提问by mchfrnc
I've met a problem with re
module in Python 3.6.5.
I have this pattern in my regular expression:
我re
在 Python 3.6.5 中遇到了模块问题。我的正则表达式中有这个模式:
'\nRevision: (\d+)\n'
But when I run it, I'm getting a DeprecationWarning
.
但是当我运行它时,我得到了一个DeprecationWarning
.
I searched for the problem on SO, and haven't found the answer, actually - what should I use instead of \d+
? Just [0-9]+
or maybe something else?
回答by ACascarino
Python 3 interprets string literals as Unicode strings, and therefore your \d
is treated as an escaped Unicode character.
Python 3 将字符串文字解释为 Unicode 字符串,因此您将\d
被视为转义的 Unicode 字符。
Declare your RegEx pattern as a raw string instead by prepending r
, as below:
将您的 RegEx 模式声明为原始字符串,而不是在前面加上r
,如下所示:
r'\nRevision: (\d+)\n'
This also means you can drop the escapes for \n
as well since these will just be parsed as newline characters by re
.
这也意味着您也可以删除转义\n
符,因为它们只会被re
.