Write this statement in a comprehensive way

Viewed 54

Im starting to learn Python and programming in general. While doing a statements assessment test, I ran into a syntax problem that has no sense to me. I get a syntax error in the second for.

Thank you!

st = 'Print only the words that start with s in this sentence'
listst = st.split()
for word in listst:
    if word[0] == 's':
        print(word)
#in one sentence?
startwiths = [word if word[0] == 's' for word in listst]
3 Answers

The if statement goes at the end of a list comprehension. So rewrite your last line to be:

startwiths = [word for word in listst if word[0] == 's']

You can also further simplify you code by replacing word[0] == 's' with the builtin string startswith function:

startwiths = [word for word in listst if word.startswith('s')]

I hope this is helpful!

Try this:

startwiths = [word for word in listst if word[0] == 's']

More info about list comprehensions in python can be found here

list_comp=[word for word in listst if word.lower()[0]=='s']

You can also use .startswith

list_comp=[word for word in listst if word.lower().startswith('s')]
Related