简体   繁体   中英

For-loop string replacement

In a for-loop I attempt to overwrite string-type variables.

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" . It should say "Item 1 Item 1"

I also tried item = item.replace("Item 2","Item 1") . Same result.

What prevents "Item 2" from getting replaced?

Update:

Similar to Changing iteration variable inside for loop in Python but with strings, not integers.

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")

You're re-assigning the temporary variable item which is assigned on every iteration of the for-loop. 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" . 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

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