我正在学习如何替换字符串中的子字符串的脚本,我偶然发现了while循环,并且我不了解使用after和after变量的用途和逻辑,以及通常情况下while循环的结果。我在网上检查了一下,发现它们使用了replace方法,但是我想了解这个常规步骤和逻辑。
things = "tree, box, chair, lamp, \n" \
"desk, cat, dog, grass, \n" \
"pig, box, lamp, shelf"
print(things)
print()
old_item = input("Old item: ")
new_item = input("New item: ")
len_old_item = len(old_item) # i didn't get why they added this.
i = things.find(old_item)
while i > 0:
before = things[:i] # i don't get how this part works
after = things[i+len_old_item:] # i don't get how this part works
things = before + new_item +after # i don't get how this part works
i = things.find(old_item) # i don't get how this part works
print()
print(things)
输出要求用户输入列表中的旧项目,然后用新项目将其替换为事物列表。