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.
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')]
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
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.