Python Program to Swap First Two Characters of Two Strings and Merge Them

Last updated 4 months ago | 197 views 75     5

Tags:- Python

String manipulation is an essential skill in Python programming, and today, we’ll explore a fun and creative problem!

Problem Statement:
Given two strings, we will:

  1. Swap the first two characters of each string.
  2. Combine them into a single string, separated by a space.

Sounds interesting? Let’s dive right into the solution!

 


 

Python Solution

To achieve this, we will:

  • Check if both strings have at least two characters.
  • Swap the first two characters of both strings.
  • Concatenate them with a space separator and return the result.

✅ Python Code Implementation

def swap_first_two_chars(str1, str2):
    if len(str1) < 2 or len(str2) < 2:
        return "Both strings must have at least two characters!"

    swapped_str1 = str2[:2] + str1[2:]  # Swap first 2 chars
    swapped_str2 = str1[:2] + str2[2:]  

    return swapped_str1 + " " + swapped_str2  # Combine with space

# Example usage
print(swap_first_two_chars("hello", "world"))  # Output: wello horld
print(swap_first_two_chars("abc", "xyz"))      # Output: xyc abz
print(swap_first_two_chars("hi", "there"))     # Output: th hiere
print(swap_first_two_chars("a", "bc"))         # Output: Error message

 


 

How It Works?

Example 1: "hello" & "world"

  • Swap first two characters: "he" ↔ "wo"
  • New strings: "wello" & "horld"
  • Final result: "wello horld"

Example 2: "abc" & "xyz"

  • Swap "ab" ↔ "xy"
  • New strings: "xyc" & "abz"
  • Final result: "xyc abz"

Edge Cases Handled

✅ If a string has less than two characters, the function returns an error message.

 


 

Why Use This Approach?

Simple & Efficient – Uses Python string slicing for quick manipulation.
Handles Edge Cases – Ensures valid input before swapping.
Great for Practice – Enhances understanding of string indexing & concatenation.

This technique is a great way to sharpen your Python skills while having fun with strings! Try it out and experiment with different inputs!