184k views
0 votes
The function below takes a single string parameter: sentence. Complete the function to return a list of strings that are in the sentence that contain a lowercase letter 'a'. Hint: you may find the split method and in operator useful in solving this problem.

User Nick Forge
by
7.6k points

1 Answer

3 votes

Answer:

#section 1

def listofWordswitha(text):

''' This function prints out every word in a string with the letter 'a' '''

tex = text.split()

new = []

#section 2

for word in tex:

for char in word:

if char == 'a':

new.append(word)

break

return new

Step-by-step explanation:

#section 1

You must first define your function and give it one argument that represents the the string that you will pass to it.

It is always good to have a doc-string that tells you what a function does, so i have also included one.

Next, you split the string using the split method that creates a list out of a string. Finally in this section you create a new list that will hold all the values with 'a'.

#section 2

The choice of words used here are intentional to make it easy to understand.

FOR every WORD in the list and FOR every CHARACTER in the WORD.

IF there is a CHARACTER 'a' contained in the word, ADD that WORD to the NEW LIST.

the append method is used to add new words to the list.

A break is used to ensure we don't have any duplication because some words can have two or more occurrence of 'a' in them. so whenever the loop sees a word with 'a', it appends it and moves to the next word.

Lastly, we return the new list.

I will take your question and use it to test the code and attach the results for you.

The function below takes a single string parameter: sentence. Complete the function-example-1
User Gineer
by
8.1k points