SeekNDestroy
SeekNDestroy

Reputation: 61

Program to Remove Letters Keeps Printing Previous Output

I have been working on a program that prompts the user to enter a word and a letter they want to remove. The process works the first time and does what it needs to properly, printing the new word with the removed letter. Yet the second time around when I try entering another letter, it prints the previous word with the removed letter, as well as the latest.

For example, if I entered "hello" and said I wanted to remove an "e", it would print "hllo". The second time, if I said remove an "o", it for some odd reason prints "hllohll" --the last three letters are correct, but I don't want the previous word. It then goes on to ruin the code processing for the rest of the rounds too.

Does anyone know why this is happening and how I should resolve it?

Here's my code so far:

new_word = ""
removed_letter = ""

word = str(input("Please enter a word: "))

while removed_letter != "done":
    removed_letter = str(input("\nWhich letter do you want to see removed? (done to exit): "))
    for num in range(len(word)):
        if word[num] == removed_letter:
            new_word += ""

        else:
            new_word += word[num]
    print(new_word)
    word = ""
    word = new_word

Upvotes: 0

Views: 127

Answers (3)

Cheche
Cheche

Reputation: 1516

I'd suggest to use .replace() method to replace the letter that wants to be removed. It makes code simpler:

word = str(input("Please enter a word: "))
edited_word = word

while removed_letter != "done":
    removed_letter = str(input("\nWhich letter do you want to see removed? (done to exit): "))
    edited_word = edited_word .replace(removed_letter, '')
    print(edited_word)

Upvotes: 0

Magofoco
Magofoco

Reputation: 5446

Your new_word has to be inside the loop, otherwise it keeps adding to itself.

word = str(input("Please enter a word: "))

removed_letter = ""

while removed_letter != "done":
    new_word = ""
    removed_letter = str(input("\nWhich letter do you want to see removed? (done to exit): "))
    for num in range(len(word)):
        if word[num] == removed_letter:
            new_word += ""


        else:
            new_word += word[num]
    print(new_word)
    word = ""
    word = new_word

Upvotes: 2

You keep appending to new_word, but you never clear it. Do new_word = "" inside your loop.

Upvotes: 1

Related Questions