python - 替代 Python 字符串替换方法

标签 python string

我想从段落中删除某些词,例如“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/

相关文章:

python - 计算字符串中子字符串出现的次数

python - 如何用python解析tsv文件?

python - 类型错误 : 'numpy.float64' object does not support item assignment

string - 将字符串的一部分提取到bash中的变量

arrays - 从 Fortran 中的子例程返回分配的字符串数组?

python-pygame 矩形不会绘制/渲染

python - 导入中的奇怪行为

c++ - 字符串问题

C++程序指令

string - 如何获取 Golang 字符串的最后 X 个字符?