I have the following string:
my_string = "This is an example string, ex , excatly , index , hyperextension"
I want to remove all words that start with ex
in Python.
So the result I want would be:
remove_words_that_start_with_ex("my_string")
print(my_string)
Desired result:
This is an string, , , index , hyperextension
I tried doing something like this:
main_str = " ".join(filter(lambda x:x[0,1]!='ex', main_str.split()))
but it only works with one character, not 2 ("ex").
You can use python's built-in startswith
method like so:
>>> 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
Now in case you just want to fix your lambda, here is a fix:
>>> print " ".join(filter(lambda x: x[0:2]!='ex', my_string.split()))
This is an string, , , index , hyperextension
You can use re.sub
to do this
>>> 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'
You can use 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)
Output:
'This is an string, ex , , index , hyperextension'
Or, by providing a lambda
:
final_string = re.sub('\w+', lambda x:'' if x.group().startswith('ex') else x.group(), my_string)
Output:
'This is an string, , , index , hyperextension'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.