Reputation: 1
Here is the code to find the words start with a in the sentence: "This is an apple tree."
st = 'This is an apple tree'
for word in st.split():
if word[0]=='a':
print(word)
I want to make it to function, and takes in any sentence I want, how to to that? Here is the code I came up, but is not doing what I want.
def find_words(text):
for word in find_words.split():
if word[0]=='a':
print(word)
return find_words
find_words('This is an apple tree')
Thank you.
Upvotes: 0
Views: 194
Reputation: 525
You can use the below code. It will provide the list of words which has a word starts with 'a'.
This is simple list comprehension with if clause. Split without argument by default splits the sentence by space and startswith method helps to filter 'a'.
sentence = 'This is an apple tree'
words = [word for word in sentence.split() if word.startswith('a')]
Upvotes: 3
Reputation: 198
If you want to print the result try this:
st = 'This is an apple tree'
def find_words(text):
for word in text.split():
if word.startswith('a'):
print(word)
find_words(st)
Upvotes: 1
Reputation: 739
The problem is how you are defining the for loop. It should be:
for word in text.split(' '):
...
Just because text is the parameter in your defined function
Upvotes: 1