簡體   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