索引错误:字符串超出范围,但它不应超出范围?
问题描述:
好吧,我正在制作一个编码器/解码器,目前我正在测试以查看我的想法是否可行,但我不断收到错误,告诉我我的字符串索引超出范围,当它不应超出范围首先。索引错误:字符串超出范围,但它不应超出范围?
message = "abc"
#Should come out as 212223
translated = ' '
n = 1
while n >= 0:
t = message[n]
if t == 'a':
translated = translated + '21'
elif t == 'b':
translated = translated + '22'
elif t == 'c':
translated = translated + '23'
while n <= len(message):
n = n + 1
print(translated)
这让我感觉良好,所以我有一个很难寻找能解决我在做什么适当的帮助,所以我可以有一些帮助?一个链接,一个解决方案,我做错了什么以及如何解决它?谢谢
答
n = 0
while n >= 0:
你有一个无限循环,你继续增加n
。 在某一点message[n]
将超出范围。
您应该将while n <= len(message):
作为您的主循环而不是当前的循环。
一个更好的办法,是在message
与for
循环直接迭代:
for t in message:
if t == 'a':
translated = translated + '21'
elif t == 'b':
translated = translated + '22'
elif t == 'c':
translated = translated + '23'
答
这里:
while n <= len(message):
n = n + 1
如果需要更改为:
while n < len(message):
n = n + 1
的最后一个索引的字符串将为len(message) - 1
,因为索引编制从0. 但是,我会立即将n设置为len(message) - 1。
答
因为在最后一个循环中,您正在使用t = message [3] ..这是您错误的原因。如果消息变量包含“abc”,则只能访问t = message [0],t = message [1],t = message [2]。所以试试这个
message = "abc"
#Should come out as 212223
translated = ' '
n = 1
while n >= 0:
t = message[n-1]
if t == 'a':
translated = translated + '21'
elif t == 'b':
translated = translated + '22'
elif t == 'c':
translated = translated + '23'
while n <= len(message):
n = n + 1
print(translated)