pythonstringconcatenationnewline

Merge multiline strings horizontally


I have multiple strings containing new lines. I want to merge them horizontally so all the first lines are concatenated together, as are the second lines, third lines, and so forth.

That is:

"""line 1 
line 2 
line 3 
line 4"""

+

"""addition 1 
addition 2 
addition 3 
addition 4"""

=

"""line 1 addition 1
line 2 addition 2
line 3 addition 3
line 4 addition 4"""

But with way more than two entries.

How can I do this?


Solution

  • You can use list comprehension and str.join to concatenate the strings:

    s1 = """line 1
    line 2
    line 3
    line 4"""
    
    s2 = """addition 1
    addition 2 
    addition 3 
    addition 4"""
    
    result = "\n".join([" ".join(elem) for elem in zip(s1.split("\n"), s2.split("\n"))])
    print(result)
    

    Output:

    line 1 addition 1
    line 2 addition 2 
    line 3 addition 3 
    line 4 addition 4