How to Merge Two Strings Character by Character in Python

Interleave characters from two strings, appending any surplus characters from the longer string at the end.

Easy Python 3.9+ Aug 9, 2026 Strings & text 14 views 0 copies

Python code

26 lines
Python 3.9+
def merge_texts(left: str, right: str) -> str:
    """
    Merges two strings by interleaving their characters:
    first char from left, first from right, then second from left,
    second from right, and so on. If one string is longer, the
    remaining characters are appended at the end.

    Example:
    merge_texts("abc", "1234") -> "a1b2c34"
    """
    result = []
    min_len = min(len(left), len(right))
    for i in range(min_len):
        result.append(left[i])
        result.append(right[i])
    result.append(left[min_len:])
    result.append(right[min_len:])
    return "".join(result)


if __name__ == "__main__":
    text1 = "hello"
    text2 = "world"
    merged = merge_texts(text1, text2)
    print(merged)
    print(len(merged))

Output

stdout
hweolrllod
10

How it works

The function merge_texts builds a new string by iterating up to the length of the shorter input, appending one character from each string per loop step. After the loop, the remaining slice of the longer string (if any) is appended, preserving the original character order. Using a list and ''.join() is efficient because strings are immutable; repeated concatenation would create many intermediate objects. The min_len calculation ensures the loop never indexes past the end of either string.

Common mistakes

  • Forgetting to handle the remaining characters when one string is longer, which would silently drop them.
  • Using string concatenation inside the loop, which is slower for large inputs.
  • Forgetting that the result is a new string; the original strings are unchanged.

Variations

  1. Use `itertools.zip_longest` with a fill value and flatten the pairs with `chain.from_iterable`.
  2. Write a generator that yields characters alternately and then `''.join()` the result.

Real-world use cases

  • Mixing two text column values from a CSV into a single combined field for export.
  • Building a checkerboard pattern from two palette strings when generating a visual output.
  • Interleaving digits and letters to create a filename or ID from separate serial parts.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.