Python Program to Swap the First and the Last Character of a String

1. Introduction

Swapping the first and last character of a string is a common string manipulation task. This operation is typically used in problems involving string transformation or obfuscation. Python's ability to handle string slicing makes this task simple and efficient.

2. Program Steps

1. Define the input string.

2. Check if the string length is sufficient to perform a swap.

3. Use string slicing to isolate the first and last characters and the middle section of the string.

4. Construct a new string with the first and last characters swapped.

5. Output the new string.

3. Code Program

# Define the input string
input_string = "hello"

# Check if the string length is greater than 1
if len(input_string) > 1:
    # Swap the first and last characters using string slicing and concatenation
    swapped_string = input_string[-1] + input_string[1:-1] + input_string[0]
    # If the string is empty or a single character, no swap needed
    swapped_string = input_string

# Print the swapped string
print(f"Original string: {input_string}")
print(f"Swapped string: {swapped_string}")


Original string: hello
Swapped string: oellh


1. input_string is initialized with the value "hello".

2. The if statement checks if the string has more than one character to avoid index errors.

3. swapped_string is constructed by:

- Taking the last character of input_string with input_string[-1]

- Adding the middle section (all characters except the first and last) with input_string[1:-1]

- Adding the first character with input_string[0]

4. If the input_string is only one character or empty, swapped_string will be the same as input_string.

5. The print statements show the original and the swapped strings. The output indicates that the first and last characters have been successfully swapped.