-2

for example I entered follwoing string ; " hello I am Mohsen" ; now I want to Print on output : "Mohsen am I hello "

please help me !

Mohsen
  • 1

2 Answers2

2

Both Corralien's and Tobi208's works, and can be combined to the shorter version;

s = "hello I am Mohsen"   
print(' '.join(s.split(' ')[::-1]))

or if you want to input the string in the terminal as a prompt;

s = input()  
print(' '.join(s.split(' ')[::-1]))
MrWorldWide
  • 418
  • 4
  • 6
  • Besides one liners, I thought it would be nice to have a solution that goes step by step for someone who's clearly new to the topic. – Tobi208 Feb 09 '22 at 10:37
1

Split by space, reverse the list, and stitch it back together.

s = " hello I am Mohsen"
words = s.split(' ')
words_reversed = words[::-1]
s_reversed = ' '.join(words_reversed)

print(s_reversed)
Tobi208
  • 1,306
  • 10
  • 17