Reputation: 69
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
Upvotes: 2
Views: 273
Reputation: 309929
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'
>>>
Upvotes: 6
Reputation: 361
s = "Joe Red"
s= s.split()
c = s[-1]+" "+s[0]
c holds "Red Joe".
Upvotes: 0
Reputation: 8400
Try this ,
>>> s= "Joe Red"
>>> words = s.split()
>>> words.reverse()
>>> print ' '.join(words)
Red Joe
>>>
Upvotes: 1
Reputation: 8692
string ="joe red"
string = string.split()
print " ".join(string[::-1])
Upvotes: 0