Reputation: 661
So i get this error:
TypeError: list indices must be integers, not str
pointing to this line of code:
if snarePattern[i] == '*':
whenever I use what I thought was simple Python
snarePattern = ['-', '*', '-', '*']
for i in snarePattern:
if snarePattern[i] == '*':
...
Is this not allowed? What don't I know?
And also, If anyone knows where I'm going with this code, can you think of an easier way to create and parse simple patterns like this??? I'm new to Python.
Thanks guys
Upvotes: 2
Views: 107
Reputation: 133514
for i in snarePattern:
goes through each item not each index:
>>> snarePattern = ['-', '*', '-', '*']
>>> for c in snarePattern:
print c
-
*
-
*
You can change it to
for i in range(len(snarePattern)):
if you really need it, but it looks like you don't, just check if c == '*'
for example.
A better way to go through indices is
for i, c in enumerate(snarePattern): # i is each index, c is each character
Upvotes: 13