以下代码的输出:
rpl = 'This is a nicely escaped newline \\n'
my_string = 'I hope this apple is replaced with a nicely escaped string'
reg = re.compile('apple')
reg.sub( rpl, my_string )
…是:
^{pr2}$…所以打印时:
I hope this This is a nicely escaped newline
is replaced with a nicely escaped string
那么python在替换另一个字符串中的“apple”时,它是在回避这个字符串吗?现在我刚做完
reg.sub( rpl.replace('\\','\\\\'), my_string )
这个安全吗?有没有办法阻止Python这么做?在
来自
help(re.sub)
[emphasis mine]:解决此问题的一种方法是传递
lambda
:Python的
re
模块使用的所有regex模式都是非转义的,包括搜索和替换模式。这就是为什么在Python中,r
修饰符通常与regex模式一起使用,因为它减少了编写可用模式所需的“回击”量。在r
修饰符出现在字符串常量之前,基本上使所有\
字符(字符串分隔符之前的字符除外)一字不差。所以,r'\\' == '\\\\'
,和{把你的例子写成
按预期工作。在
相关问题 更多 >
编程相关推荐