Search code examples
pythonloopsstartswith

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. 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]. I'm pretty sure I'm not using startswith() correctly. How would I go about making this work correctly?


Solution

  • 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. You used break which would only make your code print this since after finding the first word, it will break outside the for loop. To get all the words beginning with t, you need to get rid of the 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']