简体   繁体   中英

How to use replace() function to change string items in global list?

I`ve tried to use replace function inside of while loop. My main aim is change specific index item with different string in a global list name is tryList in the code block.

when I check tryList[counter][3].replace(tryList[counter][3],newItem) output by using print() function;

I am able to see expected string value is given but at the end when I control global list, nothing is changed.

tryList=[["asd","poi","ujm","ytr"],["qaz","plm","rfv","wxs"],["edc","wer","cvc","yhn"]] #the list has 3 different list inside 
newItem="ana" #this is the string which I want to replace with tryList`s each 3rd items of lists
loop=len(tryList) 
counter=0
while counter<loop:
    tryList[counter][3].replace(tryList[counter][3],newItem) 
    counter=counter+1

Could you please help me what am I doing wrong?

Strings are immutable, so you replace method does not alter the string itself, it creates a new, modified string. So, instead of

  lst[3].replace.replace("a", "b)

write

  lst[3] = lst[3].replace("a", "b)

Try this to change the 3rd element of each list to "ana":

tryList=[["asd","poi","ujm","ytr"],["qaz","plm","rfv","wxs"],["edc","wer","cvc","yhn"]] #the list has 3 different list inside 
newItem="ana" #this is the string which I want to replace with tryList`s each 3rd items of lists
loop=len(tryList) 
counter=0
while counter<loop:
    tryList[counter][2] = tryList[counter][2].replace(tryList[counter][2],newItem) 
    counter=counter+1

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