Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeError: list indices must be integers or slices, not str when I try to iterate lists of strings with special characters inside some of them

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading