Swap First and Last Character

Swap first and last character.

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

What's going on

Reconstruct string with swapped characters.

Key Concepts:

s[-1] is last character
s[1:-1] is middle part
s[0] is first character