Mirror individual words in a sentence, but not the sentence itself

You can use a generator to loop through each word in the string and reverse it. To reverse it, we use advanced slicing with -1 as the step value. And then we want to join all the reversed words together with a space in between each word. We can do this with str.join.

Putting the above together, we get the function:

def mirror(s):
    return ' '.join(w[::-1] for w in s.split())

examples:

>>> mirror("day time you is")
'yad emit uoy si'
>>> mirror("hello how are you")
'olleh woh era uoy'

Leave a Comment