How to reverse string in python? my input string is "Hey Gun" now i want to display "Gun Hey" as output. I have tried using slice operator like [::-1] but it won't shows proper output how it works in python?
2 Answers
Using split and reversed (a bit slower though):
>>> a
'Hey Gun'
>>> ' '.join(reversed(a.split()))
'Gun Hey'
1 Comment
Nick Young
This example has an intention that is more clear then the splicing example, i feel that in almost all cases that this example would be more maintainable and so gets a vote also. Maintainability is king, optimization overrated.
' '.join(string.split()[::-1])