为了账号安全,请及时绑定邮箱和手机立即绑定

Python正则表达式 - r前缀

Python正则表达式 - r前缀

HUX布斯 2019-08-27 12:33:44
Python正则表达式 - r前缀任何人都可以解释为什么下面的示例1有效,何时r不使用前缀?我认为r只要使用转义序列,就必须使用前缀。示例2和示例3证明了这一点。# example 1import reprint (re.sub('\s+', ' ', 'hello     there      there'))# prints 'hello there there' - not expected as r prefix is not used# example 2import reprint (re.sub(r'(\b\w+)(\s+\1\b)+', r'\1', 'hello     there      there'))# prints 'hello     there' - as expected as r prefix is used# example 3import reprint (re.sub('(\b\w+)(\s+\1\b)+', '\1', 'hello     there      there'))# prints 'hello     there      there' - as expected as r prefix is not used
查看完整描述

3 回答

?
波斯汪

TA贡献1811条经验 获得超4个赞

并非所有涉及反斜杠的序列都是转义序列。\t并且\f是,例如,但\s并非如此。在非原始字符串文字中,任何\不属于转义序列的内容都被视为另一个\

>>> "\s"'\\s'>>> "\t"'\t'

\b 然而,一个转义序列,因此示例3失败了。(是的,有些人认为这种行为很不幸。)


查看完整回答
反对 回复 2019-08-27
  • 3 回答
  • 0 关注
  • 861 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信