我有以下字符串:
my_string = "This is an example string, ex , excatly , index , hyperextension"
我想删除Python中所有以ex
开头的单词。
所以我想要的结果是:
remove_words_that_start_with_ex("my_string")
print(my_string)
所需结果:
这是一个字符串,,索引,超扩展
我试图做这样的事情:
main_str = " ".join(filter(lambda x:x[0,1]!='ex', main_str.split()))
但只能使用一个字符,不能使用2个字符(“ ex”)。
答案 0 :(得分:2)
您可以像这样使用python内置的startswith
方法:
>>> my_string = "This is an example string, ex , excatly , index , hyperextension"
>>>
>>> print ' '.join(x for x in my_string.split() if not x.startswith('ex'))
This is an string, , , index , hyperextension
现在,如果您只想修复lambda,请执行以下修复程序:
>>> print " ".join(filter(lambda x: x[0:2]!='ex', my_string.split()))
This is an string, , , index , hyperextension
答案 1 :(得分:1)
您可以使用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'
答案 2 :(得分:0)
您可以使用re.sub
:
import re
my_string = "This is an example string, ex , excatly , index , hyperextension"
final_string = re.sub('(?<=\s)ex[\w]+|(?<=^)ex[\w]+', '', my_string)
输出:
'This is an string, ex , , index , hyperextension'
或者,通过提供lambda
:
final_string = re.sub('\w+', lambda x:'' if x.group().startswith('ex') else x.group(), my_string)
输出:
'This is an string, , , index , hyperextension'