简体   繁体   English

字符串索引超出范围:IndexError

[英]String index out of range: IndexError

Don't understand why am I getting index out of range... tried finding the mistake with: http://pythontutor.com/visualize.html#mode=display不明白为什么我的索引超出范围......尝试通过以下方式找到错误: http : //pythontutor.com/visualize.html#mode=display

It "updates" the i and l , but I get the error even without finishing the word.它“更新”了il ,但即使没有完成这个词,我也会收到错误消息。

What I'm trying is to print every name that has an space no farther than its 5th character, so my expected output would be:我正在尝试打印每个空格不超过其第 5 个字符的名称,因此我的预期输出是:

Rama as
Nemo as

Code:代码:

spaceNames = ['Rama as', 'Nemo as', 'Siegss as', 'Kama', 'Gray', 'BB', 'BB']

for name in spaceNames:
    i=0
    for l in name:
        
        if i <= 4 and l[i] == " ":
          print(name)
        print(i)
        i+=1

Any help appreciated!任何帮助表示赞赏!

A trivial trace of your program, or even an eyeball check, reveals that l is a single character.对你的程序的一个微不足道的跟踪,甚至是眼球检查,都会显示l是一个单一的字符。 You're using indices up to 3. A single character has only l[0] as a legal reference.您使用的索引最多为 3。单个字符只有l[0]作为合法引用。

We have no way to "fix" your program, as we have little idea what you're trying to do.我们无法“修复”您的程序,因为我们几乎不知道您要做什么。

Figured out how to solve with both comments you guys did:想出如何解决你们所做的两个评论:

spaceNames = ['Rama as', 'Nemo as', 'Siegss as', 'Kama', 'Gray', 'BB', 'BB']

for name in spaceNames:
    i=0
    for l in name:
        if name.index(l) <=4 and name[i] == " ":
            print(name)
        i+=1

Thanks!谢谢!

There seems to be a lot of looping when you can just get most of the conditions you were looking for more efficiently.当您可以更有效地获得大部分条件时,似乎有很多循环。

spaceNames = ['Rama as', 'Nemo as', 'Siegss as', 'Kama', 'Gray', 'BB', 'BB']

for name in spaceNames:
    idx = name.find(' ')  # This returns -1 if no space
    if idx < 0 or idx > 4:
        continue  # Skip
    print(name)

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

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