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

Python 如何循环字符串并将以某个字母开头的单词添加到空列表中?,python,loops,startswith,Python,Loops,Startswith,因此,对于赋值,我必须创建一个空列表变量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.ap

因此,对于赋值,我必须创建一个空列表变量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,它只会让您的代码打印它,因为在找到第一个单词后,它会在for循环之外中断。要获得所有以t开头的单词,您需要去掉断点


试着这样做:

text=这是一个文本句子,其中的单词以字母开头 t=文本。拆分“” ls=[s表示t中的s,如果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)
代码中的问题是

你在重复每个字母,这是错误的


你需要在文本中输入两个字符。斯普利特:你为什么要加上中断符?
empty_list = []
for i in text.split(" "):
if i.startswith("t"):
    empty_list.append(i)
print(empty_list)