'Any trick or workaround for indexing a string using a variable?

import random

word_list = ['ardvark', 'baboon', 'camel']
word = random.choice(word_list)
riddle = len(word) * '_'
print(riddle)

while '_' in riddle:
    guess = input('Guess a letter: ').lower()
    for letter in word:
        index = (word.index(guess))
        if letter == guess:
            riddle[index] = letter
            print(riddle)

resulting in

     riddle[index] = letter
TypeError: 'str' object does not support item assignment

I know I know, strings are immutable but still... why? They are indexable so this just might work somehow if proper workaround is applied. Or not?



Solution 1:[1]

make riddle a list and then print it with no seperator when needed

riddle = list(len(word) * '_')


print(*riddle, sep="")

Solution 2:[2]

In python (and some other languages) strings are immutable. The workaround is to use a list instead:

import random

word_list = ['ardvark', 'baboon', 'camel']
word = random.choice(word_list)
riddle =   ['_'] * len(word)
print(''.join(riddle))

while '_' in riddle:
    guess = input('Guess a letter: ').lower()
    for letter in word:
        index = (word.index(guess))
        if letter == guess:
            riddle[index] = letter
            print(''.join(riddle))

Solution 3:[3]

You can redifine riddle in this way. However, you should also catch better the error resulting if one guesses a letter which is not contained in the word.

import random

word_list = ['ardvark', 'baboon', 'camel']
word = random.choice(word_list)
riddle = len(word) * '_'
print(riddle)

while '_' in riddle:
    guess = input('Guess a letter: ').lower()
    for letter in word:
        index = (word.index(guess))
        if letter == guess:
            riddle = riddle[:index] + letter + riddle[index+1:]
            print(riddle)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sayse
Solution 2 quamrana
Solution 3 Giovanni Tardini