Emre Çakır
Emre Çakır

Reputation: 15

Why am I getting this error TypeError: list indices must be integers or slices, not str

I've created a list of characters named 'char' I thought this code would compare the user input but I am getting a TypeError

while True:
    sorubir = input("Enter a  character  name: ")
    for i in char:
        if sorubir.upper() == char[i]:
            print (sorubir)
        else:
            sorubir = input("Try again. Enter a  character name: ")

Upvotes: 0

Views: 3640

Answers (2)

Brendan Jordahl
Brendan Jordahl

Reputation: 3

Doing

for i in char:

Unless it's a list of numbers will return the data stored in that index.

For example you could be doing

char['foo']

That will return the type of error you were getting.

Instead try using

for i in range(len(char)):

This will return an integer for each index of the list.

Upvotes: 0

DMe
DMe

Reputation: 7876

for i in char already refers to the actual character in the array. I believe you thought i to be its index. That would be written instead as for i in range(0, len(char)), where i would take an index value.

In your current code, simply changing sorubir.upper() == char[i] to sorubir.upper() == i should do the trick!

Upvotes: 3

Related Questions