Open In App

Python – Horizontal Concatenation of Multiline Strings

Last Updated : 19 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
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)



Previous Article
Next Article

Similar Reads

Proper Indentation for Multiline Strings in Python
In Python, indentation plays a crucial role in code readability and structure, especially with multiline strings. Multiline strings, defined using triple quotes (""" or '''), allow for strings that span multiple lines, preserving the formatting within the quotes. Proper indentation of these strings is important for maintaining code readability and
3 min read
How do we create multiline comments in Python?
Comments are pieces of information present in the middle of code that allows a developer to explain his work to other developers. They make the code more readable and hence easier to debug. Inline Comment An inline comment is a single line comment and is on the same line as a statement. They are created by putting a '#' symbol before the text. Synt
3 min read
Multiline String in Python
A sequence of characters is called a string. In Python, a string is a derived immutable data type—once defined, it cannot be altered. To change the strings, we can utilize Python functions like split, join, and replace. Python has multiple methods for defining strings. Single quotations (''), double quotes (" "), and triple quotes (''' ''') are all
4 min read
Multiline comments in Python
In this article, we will delve into the concept of multiline comments in Python, providing a comprehensive definition along with illustrative examples in the Python programming language on How to Comment Multiple lines in Python. What is a Multiline Comment in Python? Multiline comments in Python refer to a block of text or statements that are used
4 min read
How to create a multiline entry with Tkinter?
Tkinter is a library in Python for developing GUI. It provides various widgets for developing GUI(Graphical User Interface). The Entry widget in tkinter helps to take user input, but it collects the input limited to a single line of text. Therefore, to create a Multiline entry text in tkinter there are a number of ways. Methods to create multiline
3 min read
How to make a kivy label multiline text?
Kivy is an open source software library for the rapid development of applications equipped with novel user interfaces, such as multi-touch apps. Using Kivy on your computer, you can create apps that run on: Desktop computers: OS X, Linux, Windows.IOS devices: iPad, iPhone.Android devices: tablets, phones.Any other touch-enabled professional/home br
3 min read
Python - Alternate Strings Concatenation
The problem of getting the concatenation of a list is quite generic and we might someday face the issue of getting the concatenation of alternate elements and get the list of 2 elements containing the concatenation of alternate elements. Let’s discuss certain ways in which this can be performed. Method #1: Using list comprehension + list slicing +
3 min read
Python - Concatenation of two String Tuples
Sometimes, while working with records, we can have a problem in which we may need to perform String concatenation of tuples. This problem can occur in day-day programming. Let’s discuss certain ways in which this task can be performed. Method #1 : Using zip() + generator expression The combination of above functions can be used to perform this task
3 min read
Python - String concatenation in Heterogeneous list
Sometimes, while working with Python, we can come across a problem in which we require to find the concatenation of strings. This problem is easier to solve. But this can get complex cases we have a mixture of data types to go along with it. Let’s discuss certain ways in which this task can be performed. Method #1 : Using loop + conditions We can e
4 min read
Python - String Matrix Concatenation
Sometimes, while working with Matrix we can have a problem in which we have Strings and we need a universal concatenation of all the String present in it. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + join() We can solve this problem using list comprehension as a potential shorthand to the co
4 min read
Practice Tags :
three90RightbarBannerImg