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?
Asked
Active
Viewed 713 times
-6
-
1First step: explain how you would do it in normal language not in code! – Klaus D. Jan 12 '16 at 12:30
-
1`' '.join(string.split()[::-1])` – Avinash Raj Jan 12 '16 at 12:31
-
1This is a word reversal, not string reversal. – hazardous Jan 12 '16 at 12:41
2 Answers
6
Do splitting and then reversing and then joining.
' '.join(string.split()[::-1])

Avinash Raj
- 172,303
- 28
- 230
- 274
3
Using split
and reversed
(a bit slower though):
>>> a
'Hey Gun'
>>> ' '.join(reversed(a.split()))
'Gun Hey'

heemayl
- 39,294
- 7
- 70
- 76
-
1This 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. – Nick Young Jan 12 '16 at 13:52