gpt4 book ai didi

python - 转义 re.sub 的 repl 参数

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

我想确保 re.subrepl 参数是转义的,这样任何像 \1 这样的特殊序列都不会解释:

>>> repl = r'\1'
>>> re.sub('(X)', repl, 'X')
'X'
>>> re.sub('(X)', desired_escape_function(repl), 'X')
'\\1'

是否有一个函数可以做到这一点?我知道 re.escape存在,应该使用这个吗?

最佳答案

不要为此目的使用re.escapere.escape 用于 pattern 参数,而不是 repl 参数。

相反,请遵循 the advice of Python's documentation , 并手动将所有反斜杠替换为两个反斜杠:

>>> repl = r'\1'
>>> re.sub('(X)', repl.replace('\\', '\\\\'), 'X')
'\\1'

关于python - 转义 re.sub 的 repl 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49943270/

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