Reputation: 763
I've come across posts that demonstrate how to find a string in a list and replace, but i'm having difficulty generalizing the search to only a piece of a string.
For example
listX = ['color green', 'shape circle', 'above t']
I'd like to find all strings that begin with 'above', i've been able to do some minimal searching of a list using any
and leaving the following space 'above '
but I can't figure out how to replace what I find.
Output i'm trying to create would be:
['color green', 'shape circle', 'above']
I'd also like to figure out how to remove a string that begins with 'above' from the list all together.
Upvotes: 1
Views: 107
Reputation: 2648
Another alternative:
for idx, item in enumerate(listX):
if item.startswith('above'):
listX[idx] = 'above'
After that, we will have one or more 'above'
s, then we can remove them all.
while listX.count('above') > 0:
listX.remove('above')
Upvotes: 1
Reputation: 41
I'm not sure if this is what you are looking for, but this worked for me, it printed:
['color green', 'shape circle', 'whatever you want']
listX = ['color green', 'shape circle', 'above t']
for i in range(len(listX)):
splitting = listX[i].split(' ')
if splitting[0] == 'above':
listX[i] = 'whatever you want'
print(listX)
Upvotes: 3
Reputation: 8378
['above' if x.startswith('above') else x for x in listX]
If you would like to remove all strings that start with 'above'
then you can do something like what @JonClements mentioned in comments:
[x for x in listX if not x.startswith('above')]
Alternatively:
from itertools import filterfalse
list(filterfalse(lambda x: x.startswith('above'), listX))
Upvotes: 6