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 is 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't wrong in the code.
CodePudding user response:
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]
CodePudding user response:
The issue is that since Python is 0-indexed, you need to adjust the end range of your loop. len(y)
is one number, but the last index of an interable is always len(y) - 1
. If you adjust your loop accordingly, your issue should be fixed.
However, as another user commented, if you are set on using a while
loop, be sure to incremented it after the code block; otherwise you will always skip the first element.
while y<=len(x) - 1:
# do code
y = 1
or
while y < len(x):
# do code
y = 1
Even better, use a for
loop:
for i in range(len(x)):
# do code
CodePudding user response:
You can do this with list comprehensions.
z = [(1000 if letter == " " else 1001 if letter == "a" else 1002 if letter == "b" else '') for letter in input("input the word: ")]
x = [y for y in z if y]