How to Merge Strings in Python

Merge multiple strings or a list of text lines into one string with a custom separator

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

Python code

23 lines
Python 3.9+
def merge_strings(*parts, separator=" "):
    """Merge multiple string parts into one string with a separator."""
    return separator.join(parts)


def merge_text_lines(lines, separator="\n"):
    """Merge a list of text lines into a single string."""
    return separator.join(lines)


if __name__ == "__main__":
    first = "Hello"
    second = "world"
    third = "!"

    print(merge_strings(first, second, third))
    print(merge_strings(first, second, third, separator="-"))

    text_lines = ["First line", "Second line", "Third line"]
    print(merge_text_lines(text_lines))

    custom_lines = ["apple", "banana", "cherry"]
    print(merge_text_lines(custom_lines, separator=", "))

Output

stdout
Hello world !
Hello-world-!
First line
Second line
Third line
apple, banana, cherry

How it works

The join method on the separator string concatenates all parts, placing the separator between each element. Using *parts as a parameter collects any number of positional arguments into a tuple, making merge_strings flexible for varied input. The default separator parameters provide sensible behavior while still allowing customization. This approach avoids manual string concatenation with +, which is less efficient and produces harder-to-read code. Both functions rely on the same core join pattern, just with different default separators for different use cases.

Common mistakes

  • Forgetting to pass a list to `merge_text_lines` instead of separate arguments
  • Not accounting for trailing or leading spaces when custom separators are used
  • Assuming `join` works on non-string items without converting them first

Variations

  1. Use f-strings for simple cases: f"{first} {second} {third}"
  2. Use `str.join` directly: separator.join(list_of_strings)

Real-world use cases

  • Building a single message string from multiple log lines before writing to a log file.
  • Combining user input fields like first name and last name into a full name display.
  • Concatenating SQL query fragments or URL parameters into a final request string.

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.