繁体   English   中英

如何遍历字符串并将以某个字母开头的单词添加到空列表中?

[英]How do I loop over a string and add words that start with a certain letter to an empty list?

因此,对于赋值,我必须创建一个空列表变量empty_list = [] ,然后在字符串上进行python循环,然后将每个以't'开头的单词添加到该空列表中。 我的尝试:

text = "this is a text sentence with words in it that start with letters"
empty_list = []
for twords in text:
    if text.startswith('t') == True:
        empty_list.append(twords)
    break
print(empty_list)

这仅打印单个[t]。 我很确定我没有正确使用startswith() 我将如何正确进行这项工作?

text = "this is a text sentence with words in it that start with letters"
print([word for word in text.split() if word.startswith('t')])

为您工作的解决方案。 您还需要更换text.startswith('t')twords.startswith('t')因为您现在正在使用twords通过存储在你原来的语句的每个字迭代text 您使用的break ,因为这只会使你的代码打印this ,因为找到的第一个字后,它会破坏外的for循环。 要获得所有以t开头的单词,您需要摆脱break

text = "this is a text sentence with words in it that start with letters"
empty_list = []
for twords in text.split():
    if twords.startswith('t') == True:
        empty_list.append(twords)
print(empty_list)
> ['this', 'text', 'that']

尝试这样的事情:

text = "this is a text sentence with words in it that start with letters" t = text.split(' ') ls = [s for s in t if s.startswith('t')]

ls将成为结果列表

Python非常适合使用列表推导。

以下代码有效,

empty_list = []
for i in text.split(" "):
if i.startswith("t"):
    empty_list.append(i)
print(empty_list)

您的代码中的问题是

您在重复每个字母,那是错误的

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM