简体   繁体   English

索引错误:字符串超出范围,但不应该超出范围吗?

[英]Index error: String out of range, but it shouldn't be going out of range?

Alright so I am making an encoder/decoder and currently I'm testing to see if my idea will work, but I keep getting the error telling me my string index is out of range when it shouldn't be going out of range in the first place. 好吧,所以我正在制作编码器/解码器,目前正在测试以查看我的想法是否可行,但是我不断收到错误消息,告诉我我的字符串索引超出范围,而该字符串索引不应超出范围第一名。

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)

It makes perfect sense to me so I had a hard time searching for appropriate help that solves for what I am doing, so can I have some help? 这对我来说很有意义,所以我很难找到适合自己工作的适当帮助,那么我可以帮些忙吗? A link, a solution, what I'm doing wrong and how to fix it? 链接,解决方案,我在做什么错以及如何解决? Thanks 谢谢

n = 0
while n >= 0:

You have an infinite loop as you keep on incrementing n . 当您不断增加n ,您将遇到一个无限循环。 At some point message[n] will get out of range. 在某些时候, message[n]将超出范围。

You should move the while n <= len(message): to be your main loop instead of your current one. 您应该将while n <= len(message):移到主循环中,而不是当前循环中。

A better way will be to iterate directly over message with a for loop: 更好的方法是使用for循环直接在message上进行迭代:

for t in message:
    if t == 'a':
        translated = translated + '21'
    elif t == 'b':
        translated = translated + '22'
    elif t == 'c':
        translated = translated + '23'

Here: 这里:

while n <= len(message):
    n = n + 1

Should need changing to: 应更改为:

while n < len(message):
    n = n + 1

The last index of a string will be len(message) - 1 , as indexing starts at 0. I would just set n to len(message) - 1 instantly instead however. 字符串的最后一个索引为len(message) - 1 ,因为索引从0开始。我只是立即将n设置为len(message)-1。

Because at last loop you are using t = message[3]..It is the cause of your error. 因为在最后一个循环中您正在使用t = message [3]。这是导致错误的原因。 If you message variable contain "abc" then you can access only t = message[0], t = message[1], t = message[2]. 如果消息变量包含“ abc”,则只能访问t =消息[0],t =消息[1],t =消息[2]。 So try this 所以试试这个

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM