This is code I came across while browsing through Invent With Python. This particular chapter covers creating a basic hangman game, but the pure simplicity of how it handles displaying the missing letters struck me as incredibly elegant.
blanks = '_' * len(secretWord) for i in range(len(secretWord)): # replace blanks with correctly guessed letters if secretWord[i] in correctLetters: blanks = blanks[:i] + secretWord[i] + blanks[i+1:] for letter in blanks: # show the secret word with spaces in between each letter print(letter, end=' ')
I’m fairly confident that I would not have been able to come up with as nice of a solution; part of me says this is simply due to my lack of experience with Python and the way it handles strings and lists, but I know the same concept could be applied in Java.
On the bright side, while I wouldn’t have come up with this approach myself, at least I am able to look at code like this and instantly understand what is going on. That gives me hope.