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.
Python code
12 linesdef 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
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
- Use a generator expression directly inside `join` for improved memory efficiency on large texts.
- 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
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.