Python Forum
look at first letter in list and append word for assertion
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
look at first letter in list and append word for assertion
#1
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
Reply
#2
So what have you tried? What are your thoughts on solving this?
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
(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
Reply
#4
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Find first letter from a list DariusCG 3 2,517 Nov-27-2019, 11:08 PM
Last Post: ichabod801
  have homework to add a list to a list using append. celtickodiak 2 2,021 Oct-11-2019, 12:35 PM
Last Post: ibreeden
  getting a word from a list sheck33332 2 2,529 May-07-2019, 05:17 PM
Last Post: sheck33332

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020