首页 > 解决方案 > 在python中循环替换单词

问题描述

这段代码有什么问题:我试图在循环中运行这段代码,每个循环都需要两个参数,但它不起作用,它只运行两次然后不断打印不必要的东西。

代码:

words= "this is my computer and my computer is super computer"
wordlist = words.split(" ")
changed_wordlist=[]

while (True):
    
    replace = input("replace this: ")
    with_this = input("with this: ")
    for word in wordlist:
        
        if word == replace:
           replacedword = word.replace(replace, with_this)
           print(replacedword,end=" ") 
           changed_wordlist.append(replacedword) 
        
        elif word!= replace:
            print(word,end=" ")
            changed_wordlist.append(word)
    wordlist = changed_wordlist

标签: pythonloopsword

解决方案


我创建了一个示例,该示例将更改列表中的单词,然后在更改后打印其内容,无论是否找到该单词。尝试这个:

words = "this is my computer and my computer is super computer"
wordlist = words.split(" ")

while (True):
    replace = input("replace this: ")
    with_this = input("with this: ")

    # Iterate over the list, looking for the word
    # to replace
    for i in range(len(wordlist)):
        # If we find the word, we replace it
        if wordlist[i] == replace:
            wordlist[i] = with_this
        
    print("The list is now: " + str(wordlist))

推荐阅读