Python Practice › String Programs › Program 11

Swap the first and last characters

EasyString Programs · 11 of 106

Write a Python program to swap the first and last characters of a string.

Advertisement
Input
"SqaTool"
Output
lqaTooS

Approach

  1. Build last + middle + first.

Solution

Python
text = "SqaTool"swapped = text[-1] + text[1:-1] + text[0] if len(text) > 1 else textprint(swapped)
Output
lqaTooS

Line by line

Line 2

text[1:-1] is everything between the first and last characters.

Note

The original sample showed “IqaTooS” with a capital I, but swapping keeps the original letters, so the result is “lqaTooS”.

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs

Leave a Comment