【发布时间】: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)。 -
你的函数的第一部分似乎也放弃了最后一个词。