我有以下字符串:
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/