python - 从字符串中删除以特定字符开头的单词

标签 python string python-2.7 split

我有以下字符串:

my_string = "This is an example string, ex , excatly , index , hyperextension"

我想删除 Python 中所有以 ex 开头的单词。

所以我想要的结果是:

remove_words_that_start_with_ex("my_string")
print(my_string)

期望的结果:

This is an string, , , index , hyperextension

我尝试做这样的事情:

main_str = " ".join(filter(lambda x:x[0,1]!='ex', main_str.split()))

但它仅适用于 1 个字符,不适用于 2 个(“ex”)。

最佳答案

您可以使用re.sub来执行此操作

>>> import re
>>> my_string = "This is an example string, ex , excatly , index , hyperextension"
>>> re.sub('(?:\s)ex[^, ]*', '', my_string)
'This is an string, , , index , hyperextension'

关于python - 从字符串中删除以特定字符开头的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51343919/

相关文章:

python - 检查是否在 python 中使用递归排序

python - 阻止 Python enumerate() 将字符串拆分为字符

c - 初始化char数组的不同方式

python - PySpark — UnicodeEncodeError : 'ascii' codec can't encode character

python-2.7 - Popen.wait() 的常见/实际用途是什么

python - 我可以使用循环快速生成 x 个复选按钮吗?

python - 无法理解奇怪的 Python 导入

python - 如何使用 beautifulsoup python 提取特定 div 中的所有 href 和 src

c - 为什么我的 ANSI C 函数不保留它设置的参数值?

c++ - 字符串。 TCHAR LPWCS LPCTSTR CString。这是什么,简单快速