How to Join Multiline Text with a Semicolon Separator in Python

This code joins non-empty lines of multiline text into a single string separated by semicolons, stripping leading and trailing whitespace from each line.

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

Python code

12 lines
Python 3.9+
def join_multiline_text_with_semicolon(text):
    """Join lines of multiline text with a semicolon separator."""
    lines = [line.strip() for line in text.splitlines() if line.strip()]
    return "; ".join(lines)


if __name__ == "__main__":
    sample_text = """First line
Second line
Third line"""
    result = join_multiline_text_with_semicolon(sample_text)
    print(result)

Output

stdout
First line; Second line; Third line

How it works

The splitlines() method splits the input string at line boundaries (e.g., newline characters) and returns a list of lines. The list comprehension iterates over these lines, calls strip() to remove surrounding whitespace, and filters out any lines that become empty after stripping. The join() method concatenates the cleaned lines with a semicolon and a space as the separator, producing the final single-line string.

Common mistakes

  • Forgetting to strip lines, leaving unwanted whitespace in the output.
  • Including empty lines in the result when they should be filtered out.
  • Using `split('\n')` instead of `splitlines()` which can handle different line endings like `\r\n`.

Variations

  1. Use a generator expression directly inside `join` for improved memory efficiency on large texts.
  2. Replace the semicolon with any other delimiter or custom separator as needed.

Real-world use cases

  • Converting a multiline user-entered address or notes field into a single semicolon-separated string for storage in a database column.
  • Parsing a list of tags or keywords from a text area input into a single delimited string for an API submission.
  • Aggregating multi-line log entries into a compact summary line for alerts or notifications.

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.