The two halves. Given a string, divide it into two “equal” parts. If the length of the string is odd, the first part should contain one more character than the second part. Print a new string with the second part first and the first part second, all on a single line. Do not use the if
statement in this task.
|
s = input() middle = (len(s) + 1) // 2 print(s[middle:] + s[:middle]) |
Explanation of the Code
- Reading Input:
- The
input()
function reads a line of text from the user and stores it in the variable s
.
- Calculating the Middle Index:
middle = (len(s) + 1) // 2
- The middle index is calculated as
(len(s) + 1) // 2
. This formula ensures that if the length of the string is odd, the first part will contain one more character than the second part.
- Printing the Interchanged Halves:
print(s[middle:] + s[:middle])
- The string is sliced into two parts:
s[middle:]
and s[:middle]
.
s[middle:]
represents the second part of the string.
s[:middle]
represents the first part of the string.
- The two parts are concatenated and printed in the new order (second part first, first part second).