繁体   English   中英

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

[英]IndexError: string index out of range on my function

我正在尝试创建一个函数,该函数使我可以拆分一个字符串并将每个单词添加到列表中,然后不使用.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] ==字母:

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

就像您对问题的评论中指出的那样,您在其中也有很多问题,首先您要删除最后一个单词,可以通过以下方法解决此问题:

    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

暂无
暂无

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

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