Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Swap First and Last Character

Swap a string's endpoint characters with concatenation and slicing. Students retain the middle substring and require at least two positions before swapping.

IntermediatePhase 5 - Category 4: String TransformationExample 6 of 10
swap-first-and-last-character.py
1# Take string input
2s = input("Enter a string: ")
3
4# Swap first and last
5if len(s) >= 2:
6 result = s[-1] + s[1:-1] + s[0]
7 print(f"After swap: {result}")
8else:
9 print("String too short")

Output

Enter a string: Hello
After swap: oellH

In this one

  • Swap immutable-text endpoints
  • Retain the middle slice
  • Require two positions

How it works

  1. 1

    Require len(s) at least two.

  2. 2

    Concatenate last character, middle slice, and first character.

  3. 3

    Print result or the too-short message.

Edge cases

What happens for two characters?

What happens for two characters?

They exchange positions with an empty middle slice.

What happens for one character?

What happens for one character?

String too short is printed.

What's going on

The result begins with s[-1], continues with s[1:-1], and ends with s[0]. This assembles a new string rather than editing immutable text.

For abcd, the result is dbca. With exactly two characters, the middle slice is empty and the pair reverses. Inputs shorter than two take the message branch, avoiding indexing and duplicating a sole character.

What happens for two characters? They exchange positions with an empty middle slice.

What happens for one character? String too short is printed.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Which part keeps the middle unchanged?

Pick an answer to check it.

Question 2

What happens for two characters?

Pick an answer to check it.

Questions people ask

What happens for two characters?

They exchange positions with an empty middle slice.

What happens for one character?

String too short is printed.

Which part keeps the middle unchanged?

s[1:-1].