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

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

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')])

下面的代码有效,

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

您的代码中的问题是,

You are iterating each letter, that's wrong