-6

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?

Nick Young
  • 197
  • 7

2 Answers2

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
  • 1
    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. – Nick Young Jan 12 '16 at 13:52