Print repeated strings inside the List in Python

Asked

Viewed 288 times

0

I have a file that has several words like: apple, grape, dog, etc. I made a random to get 1 random word.

The intention is to play the hangman, the user type a letter, for example: 'r'. Then the system needs to search all the 'R' it has in the list.

Example:

['c','a','c','h','o','r','r','o']

I need him to take the position of the two repeating elements.

Take the position of the two (5 6)

So far I’ve only managed to print the repeated names but I believe the code is wrong. Could you help me?

class JogoForca():

    # Construtor
    def __init__(self, palavraSorteada):

            self.palavraSorteada = list(palavraSorteada)

            palavra = str(input('Digite a letra:\n'))

            r = self.palavraSorteada.index(palavra)
            s = self.palavraSorteada.count(palavra)
            lista = []



            for i in range(0,s):

                lista.extend([self.palavraSorteada[r]])


            print(self.palavraSorteada)
            print(lista)

# Função para ler uma palavra de forma aleatória do banco de palavras
def rand_word():
    try:
        with open("palavras.txt", "r", encoding='utf-8') as f:
            resultado = f.readlines()
            f.close()
            return resultado[random.randint(0, len(resultado))].strip()
    except IndexError as e:
        print(f'{e}')

game = JogoForca(rand_word())

2 answers

1


0

You can go through the list elements and get the index of each one with for loop. Example:

chute = "a"
palavra = "bicicleta"
positions = []
i = 0

# Como strings também são sequências, não é necessário transforma-la para uma lista aqui
for letra in palavra:
    if letra.lower() == chute.lower(): positions.append(i)
    i += 1
print(positions)

The above code works for any type of sequence (list, tuple, string, etc). I hope I’ve helped you :)

Browser other questions tagged

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