gpt4 book ai didi

Python re.sub 不返回匹配项

转载 作者:太空宇宙 更新时间:2023-11-04 08:06:36 24 4
gpt4 key购买 nike

在我的脑海中,如下:

>>> re.sub('([eo])', '_\1_', 'aeiou')

应该返回:

'a_e_i_o_u'

相反,它返回:

'a_\x01_i_\x01_u'

我确定我脑抽筋了,但我终究无法弄清楚哪里出了问题。

最佳答案

\1 在 Python 字符串文字中生成 \x01。双斜杠,或使用原始字符串文字:

>>> import re
>>> re.sub('([eo])', '_\1_', 'aeiou')
'a_\x01_i_\x01_u'
>>> re.sub('([eo])', '_\\1_', 'aeiou')
'a_e_i_o_u'
>>> re.sub('([eo])', r'_\1_', 'aeiou')
'a_e_i_o_u'

参见 The Backslash Plague在 Python 正则表达式 HOWTO 中:

As stated earlier, regular expressions use the backslash character ('\') to indicate special forms or to allow special characters to be used without invoking their special meaning. This conflicts with Python’s usage of the same character for the same purpose in string literals.

关于Python re.sub 不返回匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30238305/

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