首页 > 解决方案 > 不使用 .split() 函数从字符串中提取单词

问题描述

我对此进行了编码,以获取一个包含给定字符串 words 的列表。

data=str(input("string"))
L=[]
word=""
for i in data:
    if i.isalpha() :
        word+=i
    elif :
        L.append(word)
        word=""

但是,当我运行这段代码时,它没有显示最后一个字!

标签: pythonpython-3.x

解决方案


您没有将最后一个单词放入列表中,因为它没有非字母字符使其传递到 else 阶段并将单词保存到列表中。

让我们稍微更正一下您的代码。我假设您要检查字符串中的单词而不是字符(因为您现在正在做的是检查每个字符而不是单词。):

data=input("Input the string: ") #you don't need to cast string to string (input() returns string)
data = data+' ' # to make it save the last word
l=[] #variable names should be lowercase
word=""
for i in data:
    if i.isalpha() :
        word+=i         
    else:  # you shouldn't use elif it is else if no condition is provided
        l.append(word)
        word=" " # not to make each word connected right after each other

推荐阅读