-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?

3
  • 1
    First step: explain how you would do it in normal language not in code! Commented Jan 12, 2016 at 12:30
  • 1
    ' '.join(string.split()[::-1]) Commented Jan 12, 2016 at 12:31
  • 1
    This is a word reversal, not string reversal. Commented Jan 12, 2016 at 12:41

2 Answers 2

6

Do splitting and then reversing and then joining.

' '.join(string.split()[::-1])
Sign up to request clarification or add additional context in comments.

Comments

3

Using split and reversed (a bit slower though):

>>> a
'Hey Gun'
>>> ' '.join(reversed(a.split()))
'Gun Hey'

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.