我想从段落中删除某些词,例如“and”、“as”和“like”。有没有比通过替换更简单的方法从字符串中删除单词 --
new_str = str.replace(' and ', '').replace(' as ', '').replace(' like ', '')
比如有没有类似下面的方法?
str.remove([' and ', ' like ', ' as '])
最佳答案
是的,您可以使用 re
模块中的 sub
函数:
>>> import re
>>> s = 'I like this as much as that'
>>> re.sub('and|as|like', '', s)
'I this much that'
关于python - 替代 Python 字符串替换方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8373387/