Python中的字符串索引超出范围错误

时间:2014-07-16 22:09:26

标签: python string indexing

我一直得到一个" IndexError:字符串索引超出范围"我尝试执行此代码时出现错误消息:

#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

5 个答案:

答案 0 :(得分:3)

你太过分了一个指数:

while(num<=wordlen):

num必须严格低于长度:

while num < wordlen:

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

答案 1 :(得分:1)

你到达一个指数太远了:

while(num<=wordlen):

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

奖励:使用计数器

进行计数

Python stdlib collections提供了出色的Counter

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

答案 2 :(得分:1)

修复代码:

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')

答案 3 :(得分:0)

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

答案 4 :(得分:-1)

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

尝试更改:

wordletter = word[num-1]