Python Forum

Full Version: look at first letter in list and append word for assertion
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I have a list of names, such as: words=['cat', dog', 'lion','snake', 'fox']

I then want to write a function that looks at the words that start with c and s and validate that through an assertion as follow:

def get_words_that_start_with(letter): 
    
            return 

assertion('8a', get_words_that_start_with('c'), ['cat'])
assertion('8b', get_words_that_start_with('s'), ['snake'])
when I run my assertion, i should get correct because my function would recognize the word that start with c and s
So what have you tried? What are your thoughts on solving this?
(Feb-06-2021, 04:20 PM)buran Wrote: [ -> ]So what have you tried? What are your thoughts on solving this?

i tried to put a for loop in the function, but i am not sure about how to call two strings and also this method is 'incorrect when i call the assertions

for i in words:
        if i[0]=="c":
            return i
That's a good start.
This will return one word - the first that starts with respective char. What if there are multiple words starting with the same char (it's unclear but do you see that the assertion expects a list, so probably you need to return all words starting with same char)?
You need to start with empty list and while iterating over the list of words, append words starting with the desired char. Alternatively, you can use list comprehension. Then your function should return that list.

As a side note, PEP8 recommends using str.startswith() method instead of index, like yoi do