Search code examples
pythonstringindexingrangeout

Getting an error "string index out of range" in python


I was creating a code to encode an input word.Letters in the input text is converted to a number and stored in a list.Here is the code I used,

z=input("input the word:")
x= z.strip()
y= -1
g=[ ]

while y<=len(x):
   y=y+1
   if x[y]==" ":
       g.insert(y,1000)
   if x[y]=="a":
     g.insert(y,1001)
   if x[y]=="b":
       g.insert(y,1002)    

and so on.....

But I was getting an error ,

Traceback (most recent call last):
 File "C:\Users\USER\Desktop\enc.py", line 13, in <module> 
if x[y]==" ": 
IndexError: string index out of range 

>>>

It would be grateful if anyone showed me what's wrong in the code.


Solution

  • Look at your loop. You will run the loop even when y == len(x), and you bump the y first thing. So if the string is 3, you'll do the loop with y==4, when even x[3] is out of range. Just use a for loop. That's what they're for.

    z=input("input the word:")
    x= z.strip()
    g=[ ]
    for y in range(len(x)):
       if x[y]==" ":
           g.insert(y,1000)
       elif x[y]=="a":
           g.insert(y,1001)
       elif x[y]=="b":
           g.insert(y,1002)
    

    I would probably use for y,c in enumerate(x):, but we'll leave that as an exercise for later.

    So, even better:

    g=[]
    for c in x:
        if c==' ':
            g.append(1000)
        elif c=='a':
            g.append(1001)
        elif c=='b':
            g.append(1002)
    

    An even better approach would be data-driven:

    mapping = {
        ' ': 1000,
        'a': 1001,
        'b': 1002
    }
    g = [mapping[c] for c in x]