如何使用replace()函数更改全局列表中的字符串项?

2024-04-20 05:17:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试在while循环中使用replace函数。我的主要目标是在全局列表中使用不同的字符串更改特定的索引项名称是代码块中的tryList。你知道吗

当我使用print()函数检查tryList[counter][3].replace(tryList[counter][3],newItem)输出时

我可以看到预期的字符串值是给定的,但在最后,当我控制全局列表时,什么都没有改变。你知道吗

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

你能帮帮我吗?我做错什么了?你知道吗


Tags: the函数字符串代码名称loop目标列表
2条回答

字符串是不可变的,因此replace方法不会更改字符串本身,而是创建一个新的、经过修改的字符串。所以

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

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

尝试将每个列表的第3个元素更改为“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

相关问题 更多 >