Logo Questions Linux Laravel Mysql Ubuntu Git Menu

how to shift a string to right and reverse it in python?



Shift word to right and then reverse it.

You should take a word shift to right and reverse it then return as follows:

>>> shift_reverse('Introduction to Computer Programming')
gnimmargorP noitcudortnI ot retupmoC

I tried using this method to find the above answer but it doesnt seem to work Please help :(

s= "I Me You"
def shift_reverse(s):
    l= s.split()
    new_str= ' '.join(l[-1:] + l[:-1])
    new_str = new_str[::-1]
    return (new_str)

print (shift_reverse(s))

but the print i get is

[evaluate untitled-3.py]
eM I uoY
like image 699
Zeeran Avatar asked Nov 26 '22 06:11


2 Answers

You need to reverse each of the re-ordered list:

reordered = l[-1:] + l[:-1]
new_str = ' '.join(word[::-1] for word in reordered)
like image 186
Peter Wood Avatar answered Nov 28 '22 20:11

Peter Wood

You can join a generator expression that generates reversed words in the rotated split list:

>>> s = 'Introduction to Computer Programming'
>>> ' '.join(w[::-1] for w in (lambda l: l[-1:] + l[:-1])(s.split()))
'gnimmargorP noitcudortnI ot retupmoC'
like image 44
Shashank Avatar answered Nov 28 '22 20:11