gpt4 book ai didi

python - 如果不属于 Python 中的一组匹配模式,则删除字符串中的字符

转载 作者:太空宇宙 更新时间:2023-11-03 12:57:39 28 4
gpt4 key购买 nike

如果我有一个包含很多单词的字符串。如果字符串中的单词不是以 _ 开头,我想删除右括号。

示例输入:

this is an example to _remove) brackets under certain) conditions.

输出:

this is an example to _remove) brackets under certain conditions.

如何在不使用 re.sub 拆分单词的情况下做到这一点?

最佳答案

re.sub 接受一个可调用对象作为第二个参数,在这里派上用场:

>>> 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.'

关于python - 如果不属于 Python 中的一组匹配模式,则删除字符串中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34502684/

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