所以对于赋值,我必须创建一个空列表变量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()
。我该怎么做才能让它正常工作呢?在
试试这样的方法:
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
。在相关问题 更多 >
编程相关推荐