简体   繁体   中英

Searching for a keyword in a list of strings and replacing the entire string if it contains that keyword

I have a list of strings mylist and I'd like to search through each string to see if it has a certain keyword, lets say the keyword is "blue" . If I find the word blue in any particular string, I want to change that entire string to something completely different. So far, I have found a way to change that particular string and then print it succesfully inside my 'for' loop, but when I go to print the full list, it is no longer altered. Here is what I mean:

Input:

mylist = ['my name is bob','my favorite color is blue', 'eggs are tasty']

for i in mylist:
    if 'blue' in i:
        i = i.replace(str(i),'Found blue')
        print(i)
print(mylist)

Output:

Found blue

['my name is bob','my favorite color is blue', 'eggs are tasty']

As you can see, the print(i) replaced the string as I wanted, but the actual list wasn't changed when I printed the full list

Is there a way to alter the list in this way or do I need to approach this differently?

You need to actually assign it back into the list because strings are immutable in Python :

mylist = ['my name is bob','my favorite color is blue', 'eggs are tasty']

for i in range(len(mylist)):
    if "blue" in mylist[i]:
        mylist[i] = "Found blue" # no need to use replace if you're going to change the whole string

Alternatively, you could use a list comprehension or a map

mylist = ['my name is bob','my favorite color is blue', 'eggs are tasty']
mylist[:] = ["Found blue" if "blue" in i else i for i in mylist]

# Or
mylist = ['my name is bob','my favorite color is blue', 'eggs are tasty']
mylist[:] = list(map(lambda i: "Found blue" if "blue" in i else i, mylist))

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