To swap the two words. Given a string consisting of exactly two words separated by a space, print a new string with the positions of the first and second words swapped (i.e., the second word is printed first).
|
s = input() first_word, second_word = s.split() print(second_word, first_word) |
Explanation of the Code
- Reading Input:
- The
input()
function reads a line of text from the user and stores it in the variable s
.
- Splitting the String:
first_word, second_word = s.split()
- The
split()
method splits the string s
at the space character, resulting in a list of two words.
- The two words are assigned to the variables
first_word
and second_word
.
- Printing the Swapped Words:
print(second_word, first_word)
- The
print()
function prints the second_word
followed by the first_word
, effectively swapping their positions.