索引器错误:字符串索引超出我的函数范围

2024-09-30 04:27:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个函数,它允许我拆分字符串并将每个单词添加到列表中,然后返回以列表中某个字母开头的单词,而不使用.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

问题出在线路上

if split_text[number][0] == letter:

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


Tags: thetotextnumber列表ifis单词
1条回答
网友
1楼 · 发布于 2024-09-30 04:27:50

就像你对问题的评论所说的那样,你有几个问题,首先你放弃了最后一个词,你可以用以下方法来解决:

    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:

然后我认为当你有两个“空格”时,你的索引器问题就来了,在这种情况下,你添加了一个空字符串,因为它没有任何字符[0]是索引器错误。你可以用以下方法解决这个问题:

^{pr2}$

只是为了回答你的问题。在

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

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

相关问题 更多 >

    热门问题