2

I want to invert the order of a string. For example: "Joe Red" = "Red Joe" I believe the reverse method will not help me, since I dont want to reverse every character, just switch words

Bach
  • 6,145
  • 7
  • 36
  • 61
Joseph
  • 69
  • 4
  • 13
  • possible duplicate of [How do you reverse the words in a string using python (manually)?](http://stackoverflow.com/questions/7694977/how-do-you-reverse-the-words-in-a-string-using-python-manually) – sundar nataraj May 08 '14 at 05:52
  • possible duplicate of [Reverse the ordering of words in a string](http://stackoverflow.com/questions/1009160/reverse-the-ordering-of-words-in-a-string) – Ffisegydd May 09 '14 at 13:29

5 Answers5

6

First, you need to define what you mean by "word". I'll assume you just want strings of characters separated by whitespace. In that case, we can do:

' '.join(reversed(s.split()))

Note, this will remove leading/trailing whitespaces, and convert any consecutive runs of whitespaces to a single space character.

Demo:

>>> s = "Red Joe"
>>> ' '.join(reversed(s.split()))
'Joe Red'
>>> 
Pragmateek
  • 13,174
  • 9
  • 74
  • 108
mgilson
  • 300,191
  • 65
  • 633
  • 696
2

try this code

s = "Joe Red"
print ' '.join(s.split()[::-1])
Sharath
  • 320
  • 1
  • 2
  • 11
1

Try this ,

>>> s= "Joe Red"
>>> words = s.split()
>>> words.reverse()
>>> print ' '.join(words)
Red Joe
>>> 
Nishant Nawarkhede
  • 8,234
  • 12
  • 59
  • 81
0
string ="joe red"
string = string.split()
print " ".join(string[::-1])
sundar nataraj
  • 8,524
  • 2
  • 34
  • 46
0
s = "Joe Red"
s= s.split()
c = s[-1]+" "+s[0]

c holds "Red Joe".

Prarthana Hegde
  • 361
  • 2
  • 7
  • 18
  • what if it is "joe red ram" – sundar nataraj May 08 '14 at 05:50
  • Concatenate the strings by putting a for loop in reverse order! Thanks for the -1! – Prarthana Hegde May 08 '14 at 06:12
  • @user3193036 -- But to be fair, you didn't mention that as part of your answer and, even if you did, doing repeated concatenations in a for loop leads to quadratic time complexity. It may (or may not) matter here, BUT, that is why the other answers which use `str.join` are more common idioms in python. And since they're more common idioms, they're easier for people who have been using the language for a while to read/understand at a glance. – mgilson May 08 '14 at 06:19
  • @user3193036 i dint give u -1.but ur answer only works for two word string. u need give answer which is scalable:) – sundar nataraj May 08 '14 at 06:25
  • Alright, I'll keep all considerations in mind the next time I post an answer. Thanks :) – Prarthana Hegde May 08 '14 at 09:20