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

📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.

✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.

🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.

▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube

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]
else:
    # 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}")

Output:

Original string: hello
Swapped string: oellh

Explanation:

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.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare