Problem comparing strings and string being wrapped into two python lines

Question:

I was creating a game that scrambles words, and the user has 6 tries to guess what the word is. I'll put the code here:

import random

def main():
    while True:
        input('Presisone enter para sortear uma nova palavra.')
        palavra_oculta, dica = EscolhePalavra()
        palavra_embaralhada = EmbaralhaPalavra(palavra_oculta)
        palavra_embaralhada = palavra_embaralhada.lower()
        palavra_oculta = palavra_oculta.lower()
        tentativas = 6
        while tentativas != 0:
            print('\nA palavra embaralhada é: %s'%palavra_embaralhada)
            print('A dica é: %s'%dica)
            print('Você ainda tem %d tentativas.'%tentativas)
            palpite = input('Digite seu palpite: ')
            if palpite == palavra_oculta:
                print('Parabéns, você acertou!!!')
                break
            else:
                print('Ainda nao, tente novamente!')
                tentativas -= 1
        if tentativas == 0:
            print('Você perdeu! a palavra correta era %s.'%palavra_oculta)
        else:
            print('Parabéns, você acertou a palavra!!!')

def EscolhePalavra(): #Essa função está funcionando normalmente, a usei em outro jogo.
    lista_arquivos = {'Animais.txt' : 'Animal', 'Frutas.txt' : 'Fruta',
                      'Objetos.txt' : 'Objeto', 'Pessoas.txt' : 'Pesssoa',
                      'Profissões.txt' : 'Profissão'}
    arquivo_escolhido = random.choice(list(lista_arquivos.keys()))
    palavra = random.choice(open(arquivo_escolhido).readlines())
    dica = lista_arquivos[arquivo_escolhido]
    return(palavra, dica)

def EmbaralhaPalavra(palavra):
    palavra = list(palavra)
    random.shuffle(palavra)
    palavra = ''.join(palavra)
    return palavra

if __name__ == '__main__':
    main()

Let's get to the problems: First, with the scrambled word. For some reason I still don't know which one, when I print palavra_embaralhada , most of the time it gets broken into two lines. I've already tried to print it on a separate line in the code, but the problem persists.

The second is that the comparison between the user-written string stored in the palpite variable and the palavra_oculta almost always goes wrong. I only got it right once. As much as I type in the correct word, the program considers it to be two different strings . What I have to do?

Answer:

First, with the scrambled word. For some reason I still don't know which one, when I print scrambled_word most of the time it gets broken into two lines. I've already tried to print it on a separate line in the code, but the problem persists.

  • The problem occurs in the function EmbaralhaPalavra , assuming that the variable palavra_oculta has Bar value, use the list , the return value is a list containing ['B', 'a', 'r', '\n'] , and where does the shuffle with random.shuffle , the following happens (may vary) : ['a', 'B', '\n', 'r'] , that is, the reason for line breaks is due to new line that is created using list . To fix this, you will need to remove the new line before doing the shuffle. One way to do this is to use the rstrip method, there are other ways as well.

     def EmbaralhaPalavra(palavra): palavra = palavra.rstrip() palavra = list(palavra) random.shuffle(palavra) palavra = ''.join(palavra) return palavra

The second is that the comparison between the user-written string stored in the guess variable and the hidden_word almost always goes wrong. I only managed to "get it right" once. As much as I type in the correct word, the program considers it to be two different strings. What I have to do?

  • Same problem . Now in the EscolhePalavra function, on the line where the file opens and reads the lines:

     palavra = random.choice(open(arquivo_escolhido).readlines())

    readlines() returns everything, including if palpite == palavra_oculta.. , when comparing: if palpite == palavra_oculta.. , it is compared: Bar with Bar\n . To solve this, you can use the same solution as used in the first problem, or use the str.splitlines() method instead of readlines() , this will eliminate the line breaks .

     def EscolhePalavra(): lista_arquivos = {'Animais.txt' : 'Animal', 'Frutas.txt' : 'Fruta', 'Objetos.txt' : 'Objeto', 'Pessoas.txt' : 'Pesssoa', 'Profissões.txt' : 'Profissão'} arquivo_escolhido = random.choice(list(lista_arquivos.keys())) linhas = open(arquivo_escolhido).read().splitlines() palavra = random.choice(linhas) dica = lista_arquivos[arquivo_escolhido] return(palavra, dica)

    String comparison in Python is case-sensitive , which can affect the result of the game, as it compares the lowercase letters of the palavra_oculta variable with the value of the palpite variable, which can contain uppercase letters, also use the lower() method in palpite .

Scroll to Top
AllEscort