Thanzeer Salim
Thanzeer Salim

Reputation: 130

IndexError: string index out of range in Python code

There is an error in my code help me to correct it

This is the actual code

message=input("enter the message ") 
alphabet='abcdefghijklmnopqrstuvwxyz ' 
key=5 
encrypt='' 
for i in message:
   position=alphabet.find(i) 
   newposition=key+position 
   encrypt+=alphabet[newposition] 
   print(encrypt)

this is the error

IndexError: string index out of range

Upvotes: 0

Views: 77

Answers (3)

Kampi
Kampi

Reputation: 1891

The error occurs when you enter a w x, y, z or space. position has the value 26 when find has found a space. Now you add 5 to your position which result in 31 and your string alphabet has only a length of 27. So you have to rework the line

newposition=key+position

to get a valid number between 0 and 26. This can be done with modulo (or %) for example. You should convert the input string to lower case (or upper case and replacing your alphabet with upper case letter). Otherwise find doesn´t find any letter in your alphabet:

message="This is a test"
alphabet="abcdefghijklmnopqrstuvwxyz "
key=5
encrypt=""
for i in message.lower(): 
  position=alphabet.find(i)
  newposition=(key+position) % len(alphabet)
  encrypt+=alphabet[newposition]
  print(encrypt)

Which results in

Python 3.7.4 (default, Jul  9 2019, 00:06:43)
[GCC 6.3.0 20170516] on linux
y
ym
ymn
ymnx
ymnxf
ymnxfn
ymnxfnx
ymnxfnxf
ymnxfnxff
ymnxfnxfff
ymnxfnxfffy
ymnxfnxfffyj
ymnxfnxfffyjx
ymnxfnxfffyjxy

Upvotes: 1

Sid
Sid

Reputation: 2189

This will happen if you have w, x, y, z or a (blank) in your input. Their positions in the string are 22, 23, 24, 25 and 26. respectively.Last position in alphabet is 26. 22 + 5 = 27, which is out of range, thus the error. Same for x, y, z and , which will give 28, 29, 30 and 31 respectively.

Upvotes: 0

gboffi
gboffi

Reputation: 25023

Your problem happens when

newposition = key + position

is larger than the length of your alphabet.

You can remedy your problem using modular arithmetic

newposition = (key + position) % len(alphabet)

Upvotes: 0

Related Questions