I have the following Python code :
currentPlayers = query.getPlayers() for player in currentPlayers: return str(player['name'])+" "+str(player['score'])
And I'm getting the following error:
TypeError: list indices must be integers, not str
I've been looking for an error close to mine, but not sure how to do it, never got that error. So yeah, how can I transform it to integers instead of string? I guess the problem comes from str(player['score'])
.
The Python "TypeError: list indices must be integers or slices, not str" occurs when we use a string instead of an integer to access a list at a specific index. To solve the error, use the int() class to convert the string to an integer, e.g. my_list[int(my_str)] .
This type error occurs when indexing a list with anything other than integers or slices, as the error mentions. Usually, the most straightforward method for solving this problem is to convert any relevant values to integer type using the int() function.
Were you expecting player
to be a dict
rather than a list
?
>>> player=[1,2,3] >>> player["score"] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: list indices must be integers, not str >>> player={'score':1, 'age': 2, "foo":3} >>> player['score'] 1
player['score']
is your problem. player is apparently a list
which means that there is no 'score' element. Instead you would do something like:
name, score = player[0], player[1] return name + ' ' + str(score)
Of course, you would have to know the list indices (those are the 0 and 1 in my example).
Something like player['score']
is allowed in python, but player
would have to be a dict
.
You can read more about both lists and dicts in the python documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With