简体   繁体   中英

How do you replace certain parts of specific elements of lists?

How would you go about replacing a part of certain items in a list? (Python 3.x) Say I have a list:

x = ["part2keep removeMe", "saveme removeMe", "third length to throw it off removeMe", "element to save", "KeepThisPart"]

If I wanted to remove just the "removeMe" part, how would you go about it? I have this so far:

def replaceExampleA(x, y):
    for i in x:
        if i[len(i)-8:len(i)-1] == "removeMe":
            y.append(i[0: -12])
        else:
            y.append(i)

Edit: Just realised I made a mistake - the list is more like this: x = ["part2keep removeMe 123", "saveme removeMe 12", "third length to throw it off removeMe 83", "element to save", "KeepThisPart"]

I need to get rid of the numbers as well from the elements with "removeMe". Thanks

x = [s.replace('removeMe', '') for s in x]

This can be accomplished with list comprehension

x = ["part2keep removeMe", "saveme removeMe", "third length to throw it off removeMe"]

print(y.replace(' removeMe', '') for y in x)

You can use regex to ensure that the code is always stripping removeMe only when it occurs at the end of the string:

import re
x = ["part2keep removeMe", "saveme removeMe", "third length to throw it off removeMe", "element to save", "KeepThisPart"]
new_x = [re.sub('\sremoveMe$', '', i) for i in x]

Output:

['part2keep', 'saveme', 'third length to throw it off', 'element to save', 'KeepThisPart']

You could also use the map function

new_x = map(lambda e: e.replace('removeMe', ''), x)

The advantage of this is that you get a generator back. So in some situations this is more memory efficient. If you want a list back, just like the other answers, then you need to convert it back to a list

new_x = list(new_x)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM