Your solution is incomplete. Instead of slicing every alternate word and performing one kind of operation at a time, iterate over each one in turn, handling it as appropriate.
Here's one simple way of tackling your problem. Define a little function to do this for you.
- split the string into words
- for each word, check if it is an even word. If it is, then uppercase it. If not, reverse it
- join the transformed words into a single string
def f(n):
for i, w in enumerate(n.split()):
if i % 2 == 0:
yield w.upper() # uppercase even words
else:
yield w[::-1] # reverse odd words
>>> ' '.join(f('what is the boarding time in bangalore station'))
'WHAT si THE gnidraob TIME ni BANGALORE noitats'
What f
does is split the string into a list of words. enumerate
transforms the list into a list of (index, word) tuples. Use the index to determine whether the word is an odd or even word. yield
transforms the function into a generator, yielding one word at a time from the loop. Finally, str.join
joins each word back into a single string.
Note that there are other ways to accomplish this. I leave them as an exercise to you.