python - 不使用 .split() 函数从字符串中提取单词
问题描述
我对此进行了编码,以获取一个包含给定字符串 words 的列表。
data=str(input("string"))
L=[]
word=""
for i in data:
if i.isalpha() :
word+=i
elif :
L.append(word)
word=""
但是,当我运行这段代码时,它没有显示最后一个字!
解决方案
您没有将最后一个单词放入列表中,因为它没有非字母字符使其传递到 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
推荐阅读
- javascript - 精灵旋转与碰撞 PIXIJS
- python - 每当我在 Python 中使用 random.choice 时,都会出现错误。错误在“正文”页面中
- python - Python:函数不返回
- python - Ansible:如何将字典(不确定数量的键:值对)转换为字符串?
- php - 如何限制woocommerce产品购买
- python - python中数字映射中相关变量的约束最小化
- c# - 在 C# 中将 if 转换为三元运算符
- asp.net-mvc - AADSTS750054:SAMLRequest 或 SAMLResponse 必须作为查询字符串参数出现在 SAML 重定向绑定的 HTTP 请求中
- r - 出了点问题;缺少所有准确度指标值:模型验证
- linux - Busybox 不运行控制台