Ad

How To Remove A Character From String After Every Loop In A While Loop

- 1 answer

I'm trying to print a string that includes letters in the alphabet. After each letter the user guesses, that guessed letter would be removed from the alphabet and then printed in the console to show which letters have not been guessed yet.

So far I have tried remove(), translate(), and filter(). Every time I've tried, the letter is successfully removed but when it's time to remove another letter, the first letter reappears in the string and the second letter is now removed. Basically, the letters do not stay removed and are only gone for that one loop.

Background info: I'm making a hangman app in python3. So part of the code I'm having trouble with is within a while loop that is in a function. I'm making a hangman app in python3. So part of the code I'm having trouble with is within a while loop that is in a function.

alphabet = "abcdefghijklmnopqrstuvwxyz"
guess = " "

print("These letters haven't been guessed yet: " + alphabet.translate({ord(guess): None}))

Expected result:

(Notice that the previous do not reappear after the second input.)

guess = input("Enter a letter: ")
Enter letter: a
These letters haven't been guessed yet: bcdefghi

guess = input("Enter a letter: ")
Enter letter: h
These letters haven't been guessed yet: bcdefgi

Actual result: (Notice that the letter 'a' has reappeared after user inputs 'h' .)

guess = input("Enter a letter: ")
Enter letter: a
These letters haven't been guessed yet: bcdefghi

guess = input("Enter a letter: ")
Enter letter: h
These letters haven't been guessed yet: abcdefgi
Ad

Answer

You can use sets for this. First you create a set containing all the letters from the alphabet. Also, you want to track which are the guessed words in another set. Then, each time a user guess some letter, you add it to the guessed set. At the end, you can just print the alphabet - guessed. At the end, I just used ''.join for better output format.

alphabet = set("abcdefghijklmnopqrstuvwxyz")
guessed = set()

guess = "a"
guessed.add(guess)

print("These letters haven't been guessed yet: " + str(alphabet - guessed))
#Output: These letters haven't been guessed yet: {'c', 'd', 'y', 'r', 'i', 'h', 'g', 'o', 'q', 'x', 'v', 'k', 'j', 'z', 'p', 'n', 'u', 'm', 'l', 'b', 't', 'w', 'e', 'f', 's'}

print("These letters haven't been guessed yet: " + ''.join(alphabet - guessed))
#Output: These letters haven't been guessed yet: cdyrihgoqxvkjzpnumlbtwefs

Update from @MrFuppes: use the function sorted to print the elements from the sets in alphabetical order

print("These letters haven't been guessed yet: " + ''.join(sorted(alphabet - guessed)))
#Output: These letters haven't been guessed yet: bcdefghijklmnopqrstuvwxyz
Ad
source: stackoverflow.com
Ad