I keep getting a "list indices must be integers or slices, not str" when I run this function, and Im not sure why. This function takes an equation and splits it by number and operator ie: 1+8-9 = ['1','+','8','-','9']
def trimFunction(p):
list = re.split("([+ -])", p)
if list[0] == '':
list.remove('')
counter = 0
for x in list:
#the error happens here vvvv
if list[x].isnumeric():
counter += 1
return list, counter
Because you are iterating over each item in a list which is a string.
x
in your loop for x in list
with given ['1','+','8','-','9']
is '1', '+', '8', '-', '9', not the index of them (0, 1, 2, 3, 4).
So your loop should be:
for x in list:
if x.isnumeric():
counter += 1
return list, counter
or
for index in range(len(list)):
if list[index].isnumeric():
counter += 1
return list, counter
You need to x.isnumeric() inplace of list[x].isnumeric()
import re
def trimFunction(p):
list = re.split("([+ -])", p)
print(list)
if list[0] == '':
list.remove('')
counter = 0
for x in list:
#Correction
if x.isnumeric():
counter += 1
return list, counter
trimFunction('1+8-9')
OUTPUT (['1', '+', '8', '-', '9'], 3)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.