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.
Python code
26 linesdef 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
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
- Use `itertools.zip_longest` with a fill value and flatten the pairs with `chain.from_iterable`.
- 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
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.