IndexError:我的函数的字符串索引超出范围

时间:2014-11-03 20:41:43

标签: python string

我正在尝试创建一个函数,它允许我拆分字符串并将每个单词添加到列表中,然后返回在该列表中以某个字母开头的单词,而不使用.split()命令。 函数的第一部分(拆分字符串并将每个单词添加到列表中)完全正常。问题是当尝试返回该列表中以某个字母开头的值时。 这是我的代码:

def getWordsStartingWith(text, letter):
    split_text = [] #This is where each word is appeneded to.
    text_addition = ""  #This is where the letters from the string are added.
    number = 0
    gWSW = []
    for str in text:
        if str == ' ' or str == "'": # Checks to see whether the letter is a space or apostrophy.
            split_text.append(text_addition)
            text_addition = "" #If there is, then the letters collected so far in text_addition are apended to the list split_text and then cleared from text_addition
        else:
            text_addition += str #If not, then the letter is added to the string text_addition.

    while number < len(split_text)-1:
        if split_text[number][0] == letter:
            gWSW.append(split_text[number])
            number += 1
        else:
            number += 1
    else:
        return gWSW

问题在于

  

如果split_text [number] [0] == letter:

返回标题中所述的IndexError。我很确定它与正在使用的[number]变量有关但不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

就像对你的问题的评论所说,你有几个问题,首先你要删掉最后一个字,你可以解决这个问题:

    else:
        text_addition += str #If not, then the letter is added to the string text_addition.

    # Avoid dropping last word
    if len(text_addition):
        split_text.append(text_addition)

    while number < len(split_text)-1:
        if split_text[number][0] == letter:

然后我认为当你有两个“空格”时会出现你的IndexError问题,在这种情况下你要添加一个空字符串,因为它没有任何char [0]是indexError。您可以通过以下方式解决此问题:

    for str in text:
        if str == ' ' or str == "'": # Checks to see whether the letter is a space or apostrophy.
            if text_addition:
                # Here we avoid adding empty strings
                split_text.append(text_addition)
            text_addition = "" #If there is, then the letters collected so far in text_addition are apended to the list split_text and then cleared from text_addition
        else:
            text_addition += str #If not, then the letter is added to the string text_addition.

这只是回答你的问题。

PD:我对最后一部分的改进很少:

    result = []
    for str in split_text:
        if str.startswith(letter):
            result.add(str)
    return result