IndexError:Python代码中的字符串索引超出范围
我的代码中有一个错误。请帮助我更正它 这是实际代码IndexError:Python代码中的字符串索引超出范围,python,Python,我的代码中有一个错误。请帮助我更正它 这是实际代码 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
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)
这就是错误所在
IndexError: string index out of range
当您输入
w
x
、y
、z
或空格时,会发生错误<当find
找到空格时,code>position
的值为26
。现在,将5
添加到位置
,结果是31
,而字符串字母表
的长度只有27
。
所以你必须重做生产线
newposition=key+position
获取介于0
和26
之间的有效数字。例如,这可以通过模运算(或%
)来实现。您应该将输入字符串转换为小写(或大写,并将字母表
替换为大写字母)。否则,find
在您的字母表中找不到任何字母:
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)
导致
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
如果输入中有w
、x
、y
、z或
(空白),则会发生这种情况。它们在弦中的位置是22、23、24、25和26。分别。字母表中的最后一个位置是2622+5=27
,超出范围,因此出现错误。x、y、z和
也一样,分别为28、29、30和31。当
newposition = key + position
大于字母表的长度
你可以用电脑解决你的问题
message=input(“输入消息”)alphabet='abcdefghijklmnopqrstuvwxyz'key=5 encrypt=''对于消息中的i:position=alphabet.find(i)newposition=key+position encrypt+=alphabet[newposition]print(encrypt)这是您应该切换到len(alphabet)
,它的27actually@Kampi,对于w,x,y和z
aswell@Sid是的,就在这时我正在更新我的文本:)。处理大写字母的另一个缺点是:用于消息中的I。lower():
我也添加了它。再次感谢。
newposition = (key + position) % len(alphabet)