Python Program to swap the First and the Last Character of a string

In this article, we will explore a Python program to swap the first and last character of a string. Swapping characters within a string can be a useful operation in various scenarios, such as data manipulation, text processing, or even string encryption.

We will discuss different approaches to solve this problem efficiently using Python, provide step-by-step implementations, and include test cases to validate the program's functionality.

Understanding the Problem

Before we dive into solving the problem, let's define the requirements and constraints more explicitly.

Problem Statement We need to write a Python program that swaps the first and last character of a given string and returns the modified string.

Input The program should take a string as input.

Output The program should return the modified string with the first and last characters swapped.

Constraints

  • The input string will have at least two characters.

  • The input string may contain any printable characters, including spaces and punctuation.

Method 1: Using String Slicing

The most straightforward approach uses string slicing to extract and rearrange characters ?

def swap_first_last_character(string):
    if len(string) < 2:
        return string
    
    first_char = string[0]
    last_char = string[-1]
    modified_string = last_char + string[1:-1] + first_char
    return modified_string

# Test the function
input_string = "Hello"
output_string = swap_first_last_character(input_string)
print(f"Original: {input_string}")
print(f"Modified: {output_string}")
Original: Hello
Modified: oellH

Method 2: Using List Conversion

Convert the string to a list, swap elements, then join back to string ?

def swap_using_list(string):
    if len(string) < 2:
        return string
    
    char_list = list(string)
    char_list[0], char_list[-1] = char_list[-1], char_list[0]
    return ''.join(char_list)

# Test the function
test_strings = ["Python", "OpenAI", "ab", "Programming"]

for text in test_strings:
    result = swap_using_list(text)
    print(f"{text} ? {result}")
Python ? nythoP
OpenAI ? IpenAO
ab ? ba
Programming ? grammino

Method 3: Using String Formatting

Use f-string formatting for a more readable approach ?

def swap_with_formatting(string):
    if len(string) < 2:
        return string
    
    return f"{string[-1]}{string[1:-1]}{string[0]}"

# Test with different examples
examples = ["Hello", "World", "AI", "TutorialsPoint"]

print("Original ? Swapped")
print("-" * 20)
for example in examples:
    swapped = swap_with_formatting(example)
    print(f"{example} ? {swapped}")
Original ? Swapped
--------------------
Hello ? oellH
World ? dorlW
AI ? IA
TutorialsPoint ? tutorialsPoink

Handling Edge Cases

Let's create a robust function that handles various edge cases ?

def robust_swap(string):
    # Handle empty string or single character
    if len(string) <= 1:
        return string
    
    # Handle two characters
    if len(string) == 2:
        return string[1] + string[0]
    
    # Handle strings with more than 2 characters
    return string[-1] + string[1:-1] + string[0]

# Test edge cases
test_cases = ["", "a", "ab", "abc", "Hello World!", "12345"]

for case in test_cases:
    result = robust_swap(case)
    print(f"'{case}' ? '{result}'")
'' ? ''
'a' ? 'a'
'ab' ? 'ba'
'abc' ? 'cba'
'Hello World!' ? '!ello WorldH'
'12345' ? '52341'

Comparison

Method Readability Performance Memory Usage
String Slicing High Good Low
List Conversion Medium Moderate Higher
String Formatting High Good Low

Conclusion

We explored three different methods to swap the first and last characters of a string in Python. The string slicing method is the most efficient and readable approach for most use cases. Use list conversion when you need to perform multiple character manipulations, and string formatting when readability is the primary concern.

Updated on: 2026-03-27T11:58:31+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements