Replace letter by position

Asked

Viewed 215 times

1

I’m doing a simple python hangman game and I’d like to know if you can replace it by the letter position.

Type I want at position 1 '*' to be replaced by the letter I want.

Code:

palavra_secreta = 'alura'
enforcou = False
acertou = False
secret = '*' * len(palavra_secreta)

while not enforcou and not acertou:

    print(f'{secret}\n\n'.center(28))

    chute = str(input('Qual letra? '))
    chute = chute.strip()

    if chute in palavra_secreta:
        for i in range(0, len(palavra_secreta)):
            if chute.lower() == palavra_secreta[i].lower():
               secret = secret.replace(secret[i], chute)
    else:
        print(f'A letra {chute} não contem na palavra.')

    time.sleep(3)

    os.system('clear')   

1 answer

0


String in Python is immutable, but you could replace, for example, the 5 position character of a string as follows:

s = s[0:5] + c + s[6:]

If performance is needed, it is best to use a (mutable) character list instead of a string, but for a simple case like this, the above solution is enough.

  • Good algorithm my friend... Thank you very much.More like you said the solution with lists looks better.I managed to do with list.Vlws

  • Yeah, it gets cleaner anyway.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.