简体   繁体   English

循环字符串替换

[英]For-loop string replacement

In a for-loop I attempt to overwrite string-type variables. 在for循环中,我尝试覆盖字符串类型的变量。

item1 = "Item 1"
item2 = "Item 2"
for item in [item1, item2]:
    if item == "Item 2":
        item = "Item 1"
print (item1, item2)

The print that results says "Item 1 Item 2" . 结果显示为"Item 1 Item 2" It should say "Item 1 Item 1" 应显示"Item 1 Item 1"

I also tried item = item.replace("Item 2","Item 1") . 我也尝试了item = item.replace("Item 2","Item 1") Same result. 结果相同。

What prevents "Item 2" from getting replaced? 是什么阻止"Item 2"被替换?

Update: 更新:

Similar to Changing iteration variable inside for loop in Python but with strings, not integers. 类似于在Python中的for循环中更改迭代变量,但使用字符串,而不是整数。

I have a much longer list of variables to validate and overwrite, so a for-loop that just uses the current item for reassignment would be ideal (as opposed to item2 = "Item 1") 我有更长的变量列表需要验证和覆盖,因此只使用当前项目进行重新分配的for循环将是理想的(与item2 =“ Item 1”相对)

You're re-assigning the temporary variable item which is assigned on every iteration of the for-loop. 您将重新分配在for循环的每次迭代中分配的临时变量item So basically, you re-assign item to "Item 1" and then the interpreter immediately re-assigns it again on the next iteration to "Item 2" . 因此,基本上,您将item重新分配给"Item 1" ,然后解释器会在下一次迭代时立即将其再次重新分配给"Item 2" In any case, however, you are never mutating the original list by re-assigning this variable. 但是,无论如何,您永远都不会通过重新分配此变量来对原始列表进行变异。

If you really want the last line to print what you want, then you want to re-assign your original variables instead: 如果您确实希望最后一行打印您想要的内容,那么您想重新分配原始变量:

item1 = "Item 1"
item2 = "Item 2"
for item in [item1, item2]:
    if item == "Item 2":
        item2 = "Item 1"
print (item1, item2)

It makes more sense however to make a list of the changes, though. 不过,列出更改列表更有意义。 This is the common pattern: 这是常见的模式:

old_list = ["Item 1", "Item 2"]
new_list = []
for item in old_list:
    if item == "Item 2":
        new_list.append("Item 1")
    else:
        new_list.append(item)

print new_list

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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