Joseph
Joseph

Reputation: 69

Reverse String order

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

Answers (5)

mgilson
mgilson

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

Prarthana Hegde
Prarthana Hegde

Reputation: 361

s = "Joe Red"
s= s.split()
c = s[-1]+" "+s[0]

c holds "Red Joe".

Upvotes: 0

Nishant Nawarkhede
Nishant Nawarkhede

Reputation: 8400

Try this ,

>>> s= "Joe Red"
>>> words = s.split()
>>> words.reverse()
>>> print ' '.join(words)
Red Joe
>>> 

Upvotes: 1

Sharath
Sharath

Reputation: 338

try this code

s = "Joe Red"
print ' '.join(s.split()[::-1])

Upvotes: 2

sundar nataraj
sundar nataraj

Reputation: 8692

string ="joe red"
string = string.split()
print " ".join(string[::-1])

Upvotes: 0

Related Questions