Convert multiline string to a single line in Python

avatar

Borislav Hadzhiev

Last updated: Aug 13, 2022

banner

Photo from Unsplash

Convert multiline string to a single line in Python #

To convert a multiline string to a single line:

  1. Use the str.splitlines() method to get a list of the lines in the string.
  2. Use the str.strip() method to remove leading and trailing whitespace from each line.
  3. Use the join() method to join the list with a space separator.
main.py
my_str = """\ First line Second line Third line """ result = " ".join(line.strip() for line in my_str.splitlines()) print(repr(result)) # 👉️ "First line Second line Third line"

We used the str.splitlines() method to get a list of the lines in the string.

main.py
my_str = """\ First line Second line Third line """ # 👇️ ['First line', 'Second line', 'Third line'] print(my_str.splitlines())

The method splits the string on universal (Windows and Unix) newline characters.

We used a generator expression to iterate over the list of strings.

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we use the str.strip() method to remove any leading and trailing whitespace.

main.py
my_str = """\ First line Second line Third line """ result = " ".join(line.strip() for line in my_str.splitlines()) print(repr(result)) # 👉️ "First line Second line Third line"

The str.strip method returns a copy of the string with the leading and trailing whitespace removed.

The last step is to join the list of strings into a string.

The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

The string the method is called on is used as the separator between the elements.

In the example, we joined the strings in the list with a space separator.

However, you could also use a tab.

main.py
my_str = """\ First line Second line Third line """ result = "\t".join(line.strip() for line in my_str.splitlines()) print(repr(result)) # 👉️ "'First line\tSecond line\tThird line'"
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.