Home > Mobile >  Any trick or workaround for indexing a string using a variable?
Any trick or workaround for indexing a string using a variable?

Time:05-04

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)

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?

CodePudding user response:

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

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


print(*riddle, sep="")

CodePudding user response:

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))

CodePudding user response:

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)
  • Related