python列表中的IndexError

时间:2016-05-12 16:17:34

标签: python python-2.7

尝试编写python代码来加密字符串。

加密字符串,输出是加密字符串。

print "Enter the string "
a=raw_input()
b=len(a)+1
i=0
e=''


while i<b:
  c=''
  if i % 3 == 0:
     c+=a[i]
     e+=chr(ord(c)+5)
     del c
  elif i%3==1:
     c+=a[i]
     e+=chr(ord(c)+2)
     del c
  elif i%3==2:
     c+=a[i]
     e+=chr(ord(c)+6)
     del c     
  i=i+1

print e 

但是在运行此脚本时,会出现错误。

c+=a[i]
IndexError: string index out of range  

1 个答案:

答案 0 :(得分:1)

问题是当i等于len(a)时,您的a[i]会产生 IndexError

除此之外还有很多其他的改进,比如你总是在执行c+=a[i]而不管条件如何以及你应该试图弄清楚的更多。

相关问题