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

2024-10-02 10:25:52 发布

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

所以对于赋值,我必须创建一个空列表变量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)

这只打印了一个。我很确定我没有正确使用startswith()。我该怎么做才能让它正常工作呢?在


Tags: 字符串textin列表iswiththis单词
3条回答

试试这样的方法:

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非常适合使用列表理解。在

为您提供工作解决方案。您还需要将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"
print([word for word in text.split() if word.startswith('t')])

相关问题 更多 >

    热门问题