解决正则表达式警告:DeprecationWarning: invalid escape sequence

注意,正则匹配时,最好是使用r"\d""\\d"而不只是"\d",虽然使用"\d"可以达到预期效果,但是会报警告DeprecationWarning: invalid escape sequence '\d'。因为反斜杠会被理解为转义字符,而未识别的转义字符不同于C语言直接报错,而会被保持在字符串内。
自Python3.6,未识别的转义字符会产生DeprecationWarning;自Python3.12,这会产生SyntaxWarning;最终,在未来的Python版本里会产生SyntaxError

下面节选自Python官方文档原文:

Unlike Standard C, all unrecognized escape sequences are left in the string unchanged, i.e., the backslash is left in the result. (This behavior is useful when debugging: if an escape sequence is mistyped, the resulting output is more easily recognized as broken.) It is also important to note that the escape sequences only recognized in string literals fall into the category of unrecognized escapes for bytes literals.

Changed in version 3.6: Unrecognized escape sequences produce a DeprecationWarning.

Changed in version 3.12: Unrecognized escape sequences produce a SyntaxWarning. In a future Python version they will be eventually a SyntaxError.

文档链接

  • 12
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值