-1

I wrote this code:

asci = input('ASCII: ')
asciis = asci.split()
for i in range(len(asciis)):
    asciis[i] = int(asciis[i], 16)
    asciis[i] = str(asciis[i])
    asciis[i].lstrip('0x')
    asciis[i] = int(asciis[i])
    if asciis[i] == 0 or asciis[i] == 1 or asciis[i] == 2 or asciis[i] == 3 or asciis[i] == 4 or asciis[i] == 5 or asciis[i] == 6 or asciis[i] == 7 or asciis[i] == 8 or asciis[i] == 9 or asciis[i] == 10 or asciis[i] == 11 or asciis[i] == 12 or asciis[i] == 13 or asciis[i] == 14 or asciis[i] == 15 or asciis[i] == 16 or asciis[i] == 17 or asciis[i] == 18 or asciis[i] == 19 or asciis[i] == 20 or asciis[i] == 21 or asciis[i] == 22 or asciis[i] == 23 or asciis[i] == 24 or asciis[i] == 25 or asciis[i] == 26 or asciis[i] == 27 or asciis[i] == 28 or asciis[i] == 29 or asciis[i] == 30 or asciis[i] == 31:
        del asciis[i]

and then this appeared:

    Traceback (most recent call last):
  File "C:\Users\White & Nerdy\AppData\Local\Programs\Python\Python38-32\ascii.py", line 5, in <module>
    asciis[i] = int(asciis[i], 16)
IndexError: list index out of range

Can somebody please tell me what's wrong?

Chawie
  • 1
  • It is a bad idea to modify a list as you iterate over it. – molbdnilo May 22 '20 at 16:48
  • 1
    Because you reduce the size of `asciis` as you `del` elements. If you really wanna do so, you should iterate your list from the last element to the first. Also, you may want to replace your oversized `if-or` statement with something like `if asciis[i] in range(32)`. – keepAlive May 22 '20 at 16:48
  • You are deleting an element from the list so the index decreases by one each time. – Sri May 22 '20 at 16:48
  • You should check out the `<` and `<=` operators. – molbdnilo May 22 '20 at 16:49

1 Answers1

0

Two suggestions.

  1. Instead of mutating the list as you are iterating over it, keep track of the element you want to remove and remove it after the iteration.

  2. Instead of checking against all integers from 0-29, you can simplify that line to if (asciis[i] in range(32)):

Sri
  • 2,281
  • 2
  • 17
  • 24
  • now i get this: `Traceback (most recent call last): File "C:\Users\White & Nerdy\AppData\Local\Programs\Python\Python38-32\ascii.py", line 5, in asciis[0] = int(asciis[0], 16) TypeError: int() can't convert non-string with explicit base` – Chawie May 22 '20 at 16:55
  • that didn't work. – Chawie May 22 '20 at 17:16