[英]How do I loop over a string and add words that start with a certain letter to an empty list?
So for an assignment I have to create an empty list variable empty_list = []
, then have python loop over a string, and have it add each word that starts with a 't'
to that empty list. 因此,对于赋值,我必须创建一个空列表变量
empty_list = []
,然后在字符串上进行python循环,然后将每个以't'
开头的单词添加到该空列表中。 My attempt: 我的尝试:
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)
This just prints a single [t]. 这仅打印单个[t]。 I'm pretty sure I'm not using
startswith()
correctly. 我很确定我没有正确使用
startswith()
。 How would I go about making this work correctly? 我将如何正确进行这项工作?
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')])
Working solution for you. 为您工作的解决方案。 You also need to replace
text.startswith('t')
by twords.startswith('t')
because you are now using twords
to iterate through each word of your original statement stored in text
. 您还需要更换
text.startswith('t')
由twords.startswith('t')
因为您现在正在使用twords
通过存储在你原来的语句的每个字迭代text
。 You used break
which would only make your code print this
since after finding the first word, it will break outside the for loop. 您使用的
break
,因为这只会使你的代码打印this
,因为找到的第一个字后,它会破坏外的for循环。 To get all the words beginning with t
, you need to get rid of the break
. 要获得所有以
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']
Try something like this: 尝试这样的事情:
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
will be the resulting list ls
将成为结果列表
Python is great for using list comprehension. Python非常适合使用列表推导。
The below code works, 以下代码有效,
empty_list = []
for i in text.split(" "):
if i.startswith("t"):
empty_list.append(i)
print(empty_list)
The problem in your code is, 您的代码中的问题是
You are iterating each letter, that's wrong
您在重复每个字母,那是错误的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.