You can split your string, swap letters for each word and .join() it back together:
# example is wrong, does not swap, only puts first in the back. see below for fix
text = ' '.join( t[1:]+t[0] for t in "Hello World".split() )
print (text)
Output:
elloH orldW
This uses list comprehensionst to extract each splitted word (t
) - list slicing to move the front letter to its back (t[1:]+t[0]
) and ' '.join()
to make the list of strings back to a string.
Links:
It also works for longer strings:
elloH orldW si a eallyr verusedo trings ermt - orF ureS !
As pointed out by @Accumulation I misread the question - my example simply puts the first letter to the end of the string thats only halve the work done for swapping first and last letter:
# t[-1] is the last character put to the front,
# followed by t[1:-1] 1st to (but not including) the last character
# followed by t[0] the first character
text = ' '.join( t[-1]+t[1:-1]+t[0] for t in "Hello World".split() )
print (text)
Output:
oellH dorlW