Home > other >  TypeError: list indices must be integers or slices, not str when I try to iterate lists of strings w
TypeError: list indices must be integers or slices, not str when I try to iterate lists of strings w

Time:09-09

colloquial_numbers = ['veinti[\\s|-|]tres', 'veinti[\\s|-|]dos', 'veinti[\\s|-|]uno', 'veinte', 'tres', 'dos', 'uno']

symbolic_numbers = ['23', '22', '21', '20', '3', '2', '1']

body = ''
for n in coloquial_numbers:
    body  = """    input_text = re.sub(r"{}", "{}", input_text)\n""".format(coloquial_numbers[n], symbolic_numbers[n])
    #body  = """    input_text = re.sub(r'"""   coloquial_numbers[n]   """', '"""   symbolic_numbers[n]   """', input_text)\n"""

print(repr(body))

output:

    input_text = re.sub(r"veinti[\s|-|]*tres", "23", input_text)
    input_text = re.sub(r"veinti[\s|-|]*dos", "22", input_text)
    input_text = re.sub(r"veinti[\s|-|]*uno", "21", input_text)
    input_text = re.sub("tres", "3", input_text)
    input_text = re.sub("dos", "2", input_text)
    input_text = re.sub("uno", "1", input_text)

The error when I iterate this lists:

Traceback (most recent call last):
    body  = """    input_text = re.sub(r"{}", "{}", input_text)\n""".format(coloquial_numbers[n], symbolic_numbers[n])
TypeError: list indices must be integers or slices, not str

How could I fix this error? And why does it happen when iterating these lists of strings and with other lists it doesn't happen?

CodePudding user response:

Here you're iterating over a list of strings:

colloquial_numbers = ['veinti[\\s|-|]tres', 'veinti[\\s|-|]dos', 'veinti[\\s|-|]uno', 'veinte', 'tres', 'dos', 'uno']
...

for n in colloquial_numbers:
    ...

n is the iterating variable, which means it's assigned the VALUE of each successive element in the list, not its index. You're then running colloquial_numbers[n] which, in actual fact, is running colloquial_numbers['veinti[\\s|-|]tres'], which is incorrect python syntax, since you can't index a list by using a string

What you can do instead is:

for n in range(len(colloquial_numbers))

CodePudding user response:

The problem is your loop variable:

for n in coloquial_numbers:

This pulls out each element from colloquial_numbers and assigns it to n. e.g. n = 'veinte'

What you want is the following:

for n in range(coloquial_numbers):

So that n is the index of the list. e.g. n = 0, n = 1, etc.

  • Related