【问题标题】:String Index Out of Range Error in PythonPython中的字符串索引超出范围错误
【发布时间】:2017-04-15 03:31:32
【问题描述】:

当我尝试执行此代码时,我不断收到“IndexError: string index out of range”错误消息:

#function countLetters(word,letter) should count the number of times
#a particular letter appears in a word.

def countLetters(word, letter):

    count=0

    wordlen=len(word)
    num=0
    wordletter=""

    while(num<=wordlen):
        wordletter=word[num]
        if(wordletter==letter):
            count=count+1
        num=num+1
    return count

print(countLetters("banana", "x"))#should print 0
print(countLetters("banana", "a"))#should print 3
print(countLetters("banana", "b"))#should print 1

错误信息:

Traceback (most recent call last):
  File "C:\Users\Charlie Chiang\Desktop\9G.py", line 17, in <module>
    print(countLetters("banana", "x"))
  File "C:\Users\Charlie Chiang\Desktop\9G.py", line 10, in countLetters
    var=word[num]
IndexError: string index out of range

【问题讨论】:

  • 在我看来,正在运行的代码和您正在查看的代码是不同的。您的来源中没有var=word[num],而Traceback 似乎认为有
  • @shaktimaan:已经够近了;而不是var,而是wordletter=word[num]
  • 仅供参考,我不知道这是否用于分配,但您始终可以使用.count()。示例:"banana".count("a") 返回3
  • 是的,我正在上课,这是一项作业。

标签: python string indexing


【解决方案1】:

你把它一个索引过分了:

while(num<=wordlen):

num 必须严格低于长度:

while num < wordlen:

因为 Python 序列是从 0 开始的。长度为 5 的字符串具有索引 0、1、2、3 和 4,不是 5。

【讨论】:

  • 非常感谢!我现在觉得自己很傻,但至少我知道我做错了什么!非常感谢你,过去 2 天我一直在努力解决这个问题!谢谢!
【解决方案2】:

您到达一个索引太远了:

while(num<=wordlen):

对于文本“a”,len("a") 为 1,最后一个字母可以通过索引 0 到达。您的 while 条件允许尝试索引 1,这是不可用的。

奖励:使用计数器计数

Python stdlib collections 提供了出色的Counter

>>> from collections import Counter
>>> Counter("banana").get("x", 0)
0
>>> Counter("banana").get("a", 0)
3

【讨论】:

    【解决方案3】:

    修复您的代码:

    def countLetters(word, letter):
    
        count=0
    
        wordlen=len(word)
        num=0
        wordletter=""
        #here, because the index access is 0-based
        #you have to test if the num is less than, not less than or equal to length
        #last index == len(word) -1
        while(num<wordlen):
            wordletter=word[num]
            if(wordletter==letter):
                count=count+1
            num=num+1
        return count
    
    print(countLetters("banana", "x"))#should print 0
    print(countLetters("banana", "a"))#should print 3
    print(countLetters("banana", "b"))#should print 1
    

    更优雅的方式: str.count方法

    'banana'.count('x')
    'banana'.count('a')
    'banana'.count('b')
    

    【讨论】:

      【解决方案4】:

      因为字符串的索引从零开始,所以最高的有效索引将是 wordlen-1。

      【讨论】:

        【解决方案5】:

        索引从 0 开始,而不是 1。

        尝试改变:

        wordletter = word[num-1]
        

        【讨论】:

        • @f.rodriques 问题显示以索引 0 开头的代码。
        猜你喜欢
        • 2015-01-19
        • 1970-01-01
        • 1970-01-01
        • 2012-02-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-18
        • 1970-01-01
        • 2016-02-10
        相关资源
        最近更新 更多