How to Convert Multiline String to Single Line in Python

Recently, I was working on a text processing project where I needed to parse large chunks of text that contained multiple lines. The challenge was that I needed all this text in a single line format for my data analysis pipeline.

In Python, converting multiline strings to single lines is a common requirement when processing text files, logs, or any text data that spans multiple lines.

In this article, I’ll share five practical methods to convert multiline strings to a single line in Python, along with examples and use cases for each approach.

Convert Multiline String to Single Line in Python

Now, I am going to explain how to convert a multi-line string to a single line in Python.

Read Convert String To Object In Python

Method 1 – Use the replace() Method

The simplest way to convert a multiline Python string to a single line is by using the replace() method to substitute newline characters with empty strings or spaces.

Let’s look at an example:

def convert_multiline_to_single_line(multiline_str):
    # Replace all newlines with empty strings
    single_line = multiline_str.replace('\n', '')
    return single_line

# Example with US states data
multiline_text = """California
New York
Texas
Florida
Illinois"""

single_line_text = convert_multiline_to_single_line(multiline_text)
print(single_line_text)

Output:

CaliforniaNew YorkTexasFloridaIllinois

I executed the above example code and added the screenshot below.

Convert Multiline String to Single Line in Python

Notice that the words are joined together without spaces. If you want to preserve spaces between the lines, you can replace newline characters with a space instead:

def convert_with_spaces(multiline_str):
    # Replace all newlines with spaces
    single_line = multiline_str.replace('\n', ' ')
    return single_line

single_line_with_spaces = convert_with_spaces(multiline_text)
print(single_line_with_spaces)

Output:

California New York Texas Florida Illinois

This method is simple and works well for simple cases. However, it doesn’t handle multiple types of line breaks like \r\n (Windows) or extra whitespace efficiently.

Check out Convert String to Function in Python

Method 2 – Use the join() Method with splitlines()

A more robust approach is to use the Python splitlines() method to split the string into lines and then join them back together.

The splitlines() method breaks the string at line boundaries and returns a list of lines, handling all types of line breaks (\n, \r, or \r\n).

def convert_using_join_splitlines(multiline_str):
    # Split the string into lines and join with a space
    lines = multiline_str.splitlines()
    single_line = ' '.join(lines)
    return single_line

# Example with US cities and their populations
multiline_text = """New York City - 8.4 million
Los Angeles - 3.9 million
Chicago - 2.7 million
Houston - 2.3 million"""

result = convert_using_join_splitlines(multiline_text)
print(result)

Output:

New York City - 8.4 million Los Angeles - 3.9 million Chicago - 2.7 million Houston - 2.3 million

I executed the above example code and added the screenshot below.

Python Convert Multiline String to Single Line

This method is more versatile as it properly handles different line break types. You can also customize the joining character as needed:

# Join with a comma and space
single_line_comma = ' | '.join(multiline_text.splitlines())
print(single_line_comma)

Output:

New York City - 8.4 million | Los Angeles - 3.9 million | Chicago - 2.7 million | Houston - 2.3 million

Read Count Function in Python String

Method 3 – Use Regular Expressions

Python Regular expressions provide an efficient way to handle complex text patterns. We can use the re module to replace all kinds of whitespace:

import re

def convert_using_regex(multiline_str):
    # Replace all whitespace sequences (including newlines) with a single space
    single_line = re.sub(r'\s+', ' ', multiline_str)
    return single_line.strip()

# Example with US presidential quotes
multiline_text = """Four score and seven years ago
    our fathers brought forth on this continent,
        a new nation, conceived in Liberty,
    and dedicated to the proposition that 
all men are created equal."""

result = convert_using_regex(multiline_text)
print(result)

Output:

Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.

I executed the above example code and added the screenshot below.

How to Convert Multiline String to Single Line in Python

This method not only removes newlines but also normalizes all whitespace, including tabs and multiple spaces, into single spaces.

If you want to completely remove all whitespace:

# Remove all whitespace
no_whitespace = re.sub(r'\s+', '', multiline_text)
print(no_whitespace)

Output:

Fourscoreandservenyearsagoourbroughtforthonthiscontinent,anewnation,conceivedinLiberty,anddedicatedtothepropositionthatallmenarecreatedequal.

Check out the Encode Function in Python String

Method 4 – Use a List Comprehension with join()

For more complex transformations, we can use a Python list comprehension combined with join():

def convert_with_list_comprehension(multiline_str):
    # Use list comprehension to process each line before joining
    return ' '.join([line.strip() for line in multiline_str.splitlines()])

# Example with US national parks
multiline_text = """Yellowstone
    Grand Canyon
        Yosemite
    Zion
Great Smoky Mountains"""

result = convert_with_list_comprehension(multiline_text)
print(result)

Output:

Yellowstone Grand Canyon Yosemite Zion Great Smoky Mountains

This method gives you the flexibility to process each line individually before joining them together. For example, you can filter out empty lines:

# Filter out empty lines and strip each line
filtered_result = ' '.join([line.strip() for line in multiline_text.splitlines() if line.strip()])
print(filtered_result)

Read the Endswith Function in Python String

Method 5 – Handle Special Cases

Sometimes, you might need to handle special cases like preserving certain newlines or formatting:

def convert_preserving_paragraphs(multiline_str):
    # Split by double newlines (paragraphs) and process each paragraph
    paragraphs = multiline_str.split('\n\n')
    processed_paragraphs = []

    for paragraph in paragraphs:
        # Convert each paragraph to a single line
        processed_paragraph = ' '.join(paragraph.splitlines())
        processed_paragraphs.append(processed_paragraph)

    # Join paragraphs with a separator
    return ' || '.join(processed_paragraphs)

# Example with excerpts from US documents
multiline_text = """We the People of the United States, in Order to form a more perfect Union,
establish Justice, insure domestic Tranquility, provide for the common defence,
promote the general Welfare, and secure the Blessings of Liberty

Four score and seven years ago our fathers brought forth on this continent, 
a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal."""

result = convert_preserving_paragraphs(multiline_text)
print(result)

Output:

We the People of the United States, in Order to form a more perfect Union, establish Justice, insure domestic Tranquility, provide for the common defence, promote the general Welfare, and secure the Blessings of Liberty || Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.

This method is useful when you want to preserve some structure (like paragraphs) while converting each paragraph to a single line.

Check out Isdecimal Method in Python String

Performance Comparison

For small strings, any of these methods will work fine. However, if you’re processing large texts, performance becomes important.

Here’s a simple benchmark comparing these methods:

import timeit
import re

multiline_text = """Line 1
Line 2
Line 3
Line 4
Line 5""" * 1000

def method1():
    return multiline_text.replace('\n', ' ')

def method2():
    return ' '.join(multiline_text.splitlines())

def method3():
    return re.sub(r'\s+', ' ', multiline_text)

def method4():
    return ' '.join([line.strip() for line in multiline_text.splitlines()])

# Time each method
for method in [method1, method2, method3, method4]:
    time = timeit.timeit(method, number=100)
    print(f"{method.__name__}: {time:.6f} seconds")

In my testing, the replace() method (method1) is usually the fastest, followed closely by the join() with splitlines() method (method2). Regular expressions tend to be slower but offer more flexibility for complex patterns.

Handle Large Files

If you need to process large files line by line without loading everything into memory:

def convert_large_file(input_file, output_file):
    with open(input_file, 'r') as infile, open(output_file, 'w') as outfile:
        # Process file line by line
        current_line = ""
        for line in infile:
            # Strip newline and append to current line
            current_line += line.rstrip() + " "

            # If we hit a blank line, write the accumulated line and reset
            if line.strip() == "":
                outfile.write(current_line.strip() + "\n")
                current_line = ""

        # Write any remaining text
        if current_line:
            outfile.write(current_line.strip())

# Example usage
# convert_large_file('input.txt', 'output.txt')

This function reads the input file line by line, accumulating text until it finds a blank line (which might indicate a paragraph break), then writes the accumulated text as a single line to the output file.

I hope this article has helped you understand different ways to convert multiline strings to single lines in Python. Each method has its strengths, and the best choice depends on your specific requirements regarding performance, handling of whitespace, and special cases.

If you have any questions or suggestions, please feel free to share them in the comments section below. Happy coding!

Other Python articles you may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.