如果我有一个字符串,它包含很多单词.如果字符串中的单词不是以字母开头的话,我想删除右括号_.
示例输入:
this is an example to _remove) brackets under certain) conditions.
Run Code Online (Sandbox Code Playgroud)
输出:
this is an example to _remove) brackets under certain conditions.
Run Code Online (Sandbox Code Playgroud)
如果不拆分使用单词,我怎么能这样做re.sub呢?
re.sub 接受一个callable作为第二个参数,在这里派上用场:
>>> import re
>>> s = 'this is an example to _remove) brackets under certain) conditions.'
>>> re.sub('(\w+)\)', lambda m: m.group(0) if m.group(0).startswith('_') else m.group(1), s)
'this is an example to _remove) brackets under certain conditions.'
Run Code Online (Sandbox Code Playgroud)