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

2024-05-16 11:17:45 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有一个包含很多单词的字符串。如果字符串中的单词不是以_开头,我想去掉右括号。你知道吗

输入示例:

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

输出:

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

我怎样才能不使用re.sub拆分单词呢?你知道吗


Tags: to字符串rean示例isexamplethis
2条回答

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

如果列表理解可以做到这一点,我不会在这里使用regex。你知道吗

result = ' '.join([word.rstrip(")") if not word.startswith("_") else word
                   for word in words.split(" ")])

如果您有以下可能的输入:

someword))

你想变成:

someword)

那你就得做:

result = ' '.join([word[:-1] if word.endswith(")") and not word.startswith("_") else word
                  for word in words.split(" ")])

相关问题 更多 >