1
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?

  • 1
    Strings are immutable, meaning you can't change them. You need to build a new string. – h0r53 May 03 '22 at 16:22
  • Does this answer your question? [Why are Python strings immutable? Best practices for using them](https://stackoverflow.com/questions/8680080/why-are-python-strings-immutable-best-practices-for-using-them) – alex May 03 '22 at 16:24

3 Answers3

2

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

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


print(*riddle, sep="")
Sayse
  • 42,633
  • 14
  • 77
  • 146
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))
quamrana
  • 37,849
  • 12
  • 53
  • 71
0

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)
  • Thank you, seemed like a very original solution but would not work for word 'ardvark' even when 'a' gets guessed twice. – Mirek Hotový May 03 '22 at 17:00