【问题标题】:IndexError: string index out of range on my functionIndexError:我的函数的字符串索引超出范围
【发布时间】:2014-11-03 20:41:43
【问题描述】:

我正在尝试创建一个函数,该函数允许我拆分字符串并将每个单词添加到列表中,然后返回该列表中以某个字母开头的单词,而无需使用 .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] 变量有关,但不确定该怎么做。

【问题讨论】:

  • 这是因为您将空字符串附加到列表中。你为什么这样做,我不知道。
  • 另外,通过添加len(split_text)-1,您总是会错过最后一个字。尝试添加一些 prints 并通过每一行应该做的事情告诉自己(并查找 str.split)。
  • 你的函数的第一部分似乎也放弃了最后一个词。

标签: python string


【解决方案1】:

就像你的问题中的 cmets 指出你有几个问题,首先你放弃了最后一个词,你可以解决这个问题:

    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 问题出现在您有两个“空格”时,在这种情况下您添加了一个空字符串,并且由于它没有任何字符 [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

【讨论】:

    猜你喜欢
    • 2021-01-30
    • 1970-01-01
    • 1970-01-01
    • 2018-02-25
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多