How to Merge Strings in Python
Merge multiple strings or a list of text lines into one string with a custom separator
Python code
23 linesdef 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
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
- Use f-strings for simple cases: f"{first} {second} {third}"
- 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
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.