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
Solution 1:
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'
>>>
Solution 2:
try this code
s = "Joe Red"print' '.join(s.split()[::-1])
Solution 3:
Try this ,
>>>s= "Joe Red">>>words = s.split()>>>words.reverse()>>>print' '.join(words)
Red Joe
>>>
Solution 4:
string ="joe red"string = string.split()
print" ".join(string[::-1])
Solution 5:
s = "Joe Red"s= s.split()
c = s[-1]+" "+s[0]
c holds "Red Joe".
Post a Comment for "Reverse String Order"