How to delete an element from an Array String?

0

I'm having the following compile error:

del(alimentos[i])  
TypeError: 'str' object doesn't support item deletion

What did I do wrong? I would like to remove the typed element from the list.

My code:

dieta = []
alimentos = ""
comer = ""

while len(dieta) is not 26:
    alimentos = input("Qual o alimento? ")
    if alimentos == "fim":
        break
    dieta.append(alimentos)

i = 0
while i <= len(dieta):
    comer = input("Qual alimento deseja comer? ")
    if comer in dieta:
         print("pode comer")
         del(alimentos[i])
    i += 1
    
asked by anonymous 12.05.2017 / 22:23

2 answers

2

Your code is a bit wrong.

It's deleting according to i , but what if I do not want to delete the first element? ( 0 ) but the second ( 1 )? After all, it deletes what I "eat", right?

And also the error occurs because you're trying to get an element out of a string, not a list.

I changed a little and I left like this:

You also do not need to declare the variable alimentos nor comer at the beginning.

You can While 1: or While True: to keep it running until you type "end".

dieta = []

while 1: # Infinito
    alimentos = input("Qual o alimento? Digite 'fim' para encerrar")
    if alimentos == "fim":
        break
    else:
        dieta.append(alimentos)

while 1: # Infinito
    if len(dieta) == 0: # Se a lista esvaziar, ele encerra, senão, ele continua.
        print('Acabou a lista.')
        break
    else:
        print(dieta)
        comer = input("Qual alimento deseja comer? ")
        if comer in dieta:
            print("pode comer")
            deletar = dieta.index(comer) # Posição do item que quer deletar.
            del(dieta[deletar])
        else:
            print('Não pode comer')
    
12.05.2017 / 22:50
0

You can use remove if you have more than one equal value in the list, it removes the first occurrence found, I did a test with only one while

def cadastrar():
    dieta = []

    while True:
        if(dieta):
            print(dieta)    
        alimento = input("'fim' para encerrar \n'consumir' para comer \nQual o alimento: ").lower()
        if alimento == 'fim':
            break
        elif alimento == 'consumir':
            if(dieta):
                print(dieta)
                comer = input("Digite o alimento para consumir : ").lower()
                if comer in dieta:
                    print("pode comer")
                    dieta.remove(comer)
                else:
                    print("Não pode comer")
            else:
                print('Não tem alimentos para comer')
        else:
            dieta.append(alimento)
    return dieta
    
29.06.2017 / 16:58