Open In App
Related Articles

Python – Horizontal Concatenation of Multiline Strings

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

In Python, combining multiline strings horizontally means putting them together side by side. This is useful for joining text smoothly. Developers can use the ‘+’ symbol to merge several lines of text easily. This helps make the code easier to read and maintain. This method is handy when you need a neat and simple way to create complex strings or format output. In this article, we will learn about how to Concatenate Strings horizontally in Python.

Given a pair of strings, which is multiline, perform concatenation horizontally.

Examples:

Input : 
test_str1 = ''' 
geeks for ''' 
test_str2 = ''' 
geeks ''' 
Python

Output : 
geeks for geeks 

Explanation : 1st line joined with 1st line of 2nd string, "geeks for " -> "geeks". 

Ways of Horizontal Multiline String Concatenation in Python

There are various way to Horizontal Multiple String Concate in Python , here we are explaining some generally used method for Horizontal Multiline String Concatenation those are as follow.

Create Two Multiline String

Here, Python code initializes two multiline strings, concatenates them, and prints the original strings

Python3

# Python3 code to demonstrate working of
# Horizontal Concatenation of Multiline Strings
# initializing strings
test_str1 = '''
geeks 4
geeks'''
test_str2 = '''
is
best'''
 
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))

                    

Output :

The original string 1 is :
geeks 4
geeks
The original string 2 is :
is
best

Horizontal Multiline String Concate in Python Using zip() + split() + join() + List Comprehension

In this, we perform the task of splitting by “\n” using split(), and they are paired together using zip(). The next step is joining both the zipped strings for horizontal orientation using “\n” and join().

Example : In this example the code splits two input strings (`test_str1` and `test_str2`) into lines, then horizontally concatenates corresponding lines and prints the result.

Python3

# split lines
splt_lines = zip(test_str1.split('\n'), test_str2.split('\n'))
 
# horizontal join
res = '\n'.join([x + y for x, y in splt_lines])
 
# printing result
print("After String Horizontal Concatenation : " + str(res))

                    

Output :

After String Horizontal Concatenation : 
geeks 4is
geeksbest

Time Complexity: O(n)
Auxiliary Space: O(n)

Horizontal Multiline String Concate Using map() + operator.add + join()

In this, we use map() to with help of add() to perform concatenation, split() is used to perform initial split by “\n”.

Example : In this example code horizontally concatenates two multiline strings by combining corresponding lines using the map() function with operator.add and then joining the result using '\n'.join()

Python3

# Using map() + operator.add + join()
from operator import add
 
# using add to concat, map() to concat each lines zipped
res = '\n'.join(map(add, test_str1.split('\n'), test_str2.split('\n')))
 
# printing result
print("After String Horizontal Concatenation : " + str(res))

                    

Output :

After String Horizontal Concatenation : 
geeks 4is
geeksbest

Time Complexity: O(n) -> ( join function)
Auxiliary Space: O(n)

Python Multiline String using the itertools.zip_longest() Function, split() Function

Here, that method combines multiline strings using `itertools.zip_longest()` to pair corresponding lines, the `split()` function to break each line into words, and a for loop to concatenate the words. It ensures alignment even if the input strings have different line lengths by filling missing values with a specified filler (default is None).

Example :In this example the code horizontally concatenates corresponding lines from two strings, `test_str1` and `test_str2`, using itertools.zip_longest() to handle unequal lengths, and prints the result.

Python3

# Using itertools.zip_longest() and for loop
 
# import itertools module
import itertools
 
# split the strings
test_list1 = test_str1.split('\n')
test_list2 = test_str2.split('\n')
 
# join corresponding lines horizontally
result = ""
for line1, line2 in itertools.zip_longest(test_list1, test_list2, fillvalue=""):
    result += line1 + line2 + "\n"
 
# printing result
print("After String Horizontal Concatenation : " + str(result))

                    

Output :

After String Horizontal Concatenation : 
geeks 4is
geeksbest

Time complexity: O(n),
Auxiliary space: O(n)

Horizontal Multiline String Concate in Python Using str.splitlines() and zip()

Here, these method involves splitting multiline strings into lists of lines using `str.splitlines()`. By utilizing the `zip()` function, corresponding lines from different strings are paired together. Finally, these pairs are joined, creating a horizontally concatenated multiline string.

Example : In this example code horizontally concatenates corresponding lines from two strings (test_str1 and test_str2) using zip() and str.splitlines(), then joins the resulting pairs with spaces and combines them into a single string separated by newlines.

Python3

# Horizontal concatenation using str.splitlines() and zip()
result = '\n'.join([' '.join(pair) for pair in zip(test_str1.splitlines(), test_str2.splitlines())])
print(result)

                    

Output :

geeks 4is
geeks best

Time complexity: O(n),
Auxiliary space: O(n)

Horizontal Concatenation of Multiline String using itertools.chain() and join()

Here, the method employs the `itertools.chain()` function to combine corresponding lines from multiple multiline strings into a single iterable. The `join()` function is then used to concatenate the elements of this iterable, producing the horizontally concatenated multiline string.

Example : In this example the code horizontally concatenates corresponding lines from two strings (`test_str1` and `test_str2`) using `itertools.chain()` and `join()`, creating a new string (`result`).

Python3

# Horizontal concatenation using itertools.chain() and join()
from itertools import chain
result = '\n'.join(chain.from_iterable(zip(test_str1.splitlines(), test_str2.splitlines())))
print(result)

                    

Output :

geeks 4 is
geeks best

Time complexity: O(n)
Auxiliary space: O(n)

Horizontal Multiline String Concate using Pandas Library

Using the pandas library for horizontal multiline string concatenation involves creating a DataFrame with the multiline strings as rows, transposing it, and converting it to a string. The `to_string` method is then applied to produce the final concatenated result.

Example :In this example code horizontally concatenates two multiline strings using pandas DataFrame, transposes it, fills NaN values with an empty string, and then converts it to a string without index and header before printing.

Python3

# Horizontal concatenation using pandas
import pandas as pd
result = pd.DataFrame([test_str1, test_str2]).T.fillna('').to_string(index=False, header=False)
print(result)

                    

Output :

geeks 4 is
geeks best

Time complexity: O(n)
Auxiliary space: O(1)

Concatenate Strings Horizontally in Python using re Module

Here, method utilizes the `re` module to concatenate multiline strings. It employs the `re.sub()` function to replace newline characters with a space, effectively joining the lines. The `strip()` function is used to remove leading and trailing spaces for a cleaner result.

Example : In this example code horizontally concatenates two multi-line strings (`test_str1` and `test_str2`) by replacing newline characters with spaces using regular expressions and then prints the result.

Python3

# Horizontal concatenation using re
import re
result = re.sub(r'\n', ' ', test_str1.strip()) + '\n' + re.sub(r'\n', ' ', test_str2.strip())
print(result)

                    

Output :

geeks 4 is
geeks best

Time complexity: O(n)
Auxiliary space: O(n)



Last Updated : 19 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads