Using Python's String Slicing to Add/Replace Characters in Specific Positions

josephmads

josephmads

Posted on April 11, 2022

Using Python's String Slicing to Add/Replace Characters in Specific Positions

Intro

This article demonstrates how to replace characters in one string for the characters in another using the classic game of hangman. This may seem like it should be fairly straightforward but it is actually somewhat tricky. I will show the game code, the main problem I encountered, and a solution to that problem.

The Game

word = "hello"
perm_word = "hello"
blank = "-" * len(word)
count = len(word) * 2

print(f"This is a hangman game. Can you guess the word: {blank} in 10 tries?")

while blank != perm_word and count != 0:
    guess = input("Guess a letter: ")
    if len(guess) > 1:
        print("Type a single letter.")
        continue 
    for char in guess:
        if char in word:
            i = word.find(char) 
            blank = blank[:i] + char + blank[i+1:]
            word = word[:i] + "-" + word[i+1:]
            count -= 1
            print(blank)
            print(f"Correct! You have {count} tries left.")
        else:
            count -= 1
            print(f"Wrong. You have {count} tries left.")

if count != 0:
    print("You win!")
else:
    print("You lose.")
Enter fullscreen mode Exit fullscreen mode

THE PROBLEM

All of the code executed properly except for the lines that replace the dashes in blank with the properly guessed characters from word.

When played, the game printed a correct guess as a single character like this: e. If the second guess was an h the game would print eh instead of he.

THE SOLUTION

The key thing to remember for this problem is that strings in Python are immutable. To replace or add characters to a string, Python needs to create a copy of the string and replace characters in that copy.

The following three lines of code provide this function.

i = word.find(char) 
blank = blank[:i] + char + blank[i+1:]
word = word[:i] + "-" + word[i+1:]
Enter fullscreen mode Exit fullscreen mode

The first line gets the index value for the guessed character.

Using this value, the second line slices the dashes in blank by selecting all the index values before the guessed character with blank[:i]. It then concatenates this first slice with the guessed character and the ending slice. blank[i+1:] is the final slice. It selects all of the remaining index values after the guessed character.

Now if you guess e the game prints: -e---.

Problem solved? Not quite.

The word "hello" has two "l's". Everything works as expected for the first "l". The game prints: -el--. However, when a second "l" is guessed, the game stops at the first "l" and continues to print: -el--.

The third line of the code above solves this. It functions similarly to the previous line except it operates on word instead of blank. Essentially this makes the two variables exchange their values as characters are guessed.

If l is guessed the values of blank and word will look like this:

blank = "--l--"
word = "he-lo"

Now when the second l is guessed, word only contains one l. The game functions as it should. The values of blank and word will look like this:

blank = "--ll-"
word = "he--o"

ADDING A CHARACTER

To add a character in a specific position instead of replacing it, remove the +1 from i in the final slice. For example, if e is guessed the following line of code:

word = word[:i] + "-" + word[i:]
Enter fullscreen mode Exit fullscreen mode

will print:

"h-ello"

Thanks for reading!

💖 💪 🙅 🚩
josephmads
josephmads

Posted on April 11, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related