Convert multiline String to a Single Line in Python

avatar
Borislav Hadzhiev

Last updated: Apr 9, 2024
5 min

banner

# Table of Contents

  1. Convert multiline string to a single line in Python
  2. Strip leading whitespace from Multiline string in Python
  3. Proper indentation for multiline strings in Python

# 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"

convert multiline string to single line

The code for this article is available on GitHub

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'"

# Strip leading whitespace from Multiline string in Python

Use the textwrap.dedent() method to strip the leading whitespace from a multiline string in Python.

The textwrap.dedent method will remove the common leading whitespace from every line of the string.

main.py
from textwrap import dedent from inspect import cleandoc multiline_str = """\ first second third""" # ๐Ÿ‘‡๏ธ remove indentation # first # second # third print(dedent(multiline_str)) # ๐Ÿ‘‡๏ธ removes indentation and empty lines at the beginning and end # first # second # third print(cleandoc(multiline_str))

strip leading whitespace from multiline string

The code for this article is available on GitHub

The first example uses the textwrap.dedent method to remove the leading whitespace from the multiline string.

The textwrap.dedent() method takes a multiline string and removes the common leading whitespace from every line of the string.

The method is used to display multiline strings that are indented in the source code without any indentation.

Note that we used a backslash at the end of the first line of the multiline string.

main.py
multiline_str = """\ first second third"""
If you don't add the backslash, you'll notice that an extra newline character gets added to the string.

Make sure to close the multiline string on the same line.

main.py
multiline_str = """\ first second third""" # ๐Ÿ‘ˆ๏ธ close on same line print(multiline_str)

If you don't close the multiline string on the same line, an extra newline character gets added at the end of the string.

If your multiline string has empty lines at the beginning or end, use the inspect.cleandoc() method to remove them and remove the leading whitespace.

main.py
from inspect import cleandoc multiline_str = """ first second third """ # ๐Ÿ‘‡๏ธ removes indentation and empty lines at beginning and end # first # second # third print(cleandoc(multiline_str))

We didn't use a backslash at the end of the first line of the string and didn't close the multiline string on the same line, so the string has an empty line at the beginning and at the end.

The inspect.cleandoc() method takes care of removing the empty lines at the beginning and end and the leading whitespace.

If you don't want to remove the empty lines at the beginning and end of the multiline string, use the textwrap.dedent() method.

# Proper indentation for multiline strings in Python

To properly indent multiline strings:

  1. Add a backslash at the end of the first line.
  2. Close the multiline string on the last line.
  3. Use the dedent() and indent() methods if you need to dedent or indent the multiline string.
main.py
from textwrap import dedent, indent from inspect import cleandoc multiline_str = """\ first second third""" # ๐Ÿ‘‡๏ธ with indentation # first # second # third print(multiline_str) # ๐Ÿ‘‡๏ธ without indentation # first # second # third print(dedent(multiline_str)) # ๐Ÿ‘‡๏ธ indent the multiline string a specific number of spaces # first # second # third print(indent(multiline_str, ' ')) # ๐Ÿ‘‡๏ธ using inspect.cleandoc # (removes empty lines at beginning and end, and leading whitespace) # first # second # third print(cleandoc(multiline_str))
The code for this article is available on GitHub

# Add a backslash at the end of the first line

The first thing to note when using multiline strings is to add a backslash at the end of the first line.

main.py
multiline_str = """\ first second third""" print(multiline_str)

add backslash at end of first line

If you don't add the backslash, you'll notice that an extra newline character gets added to the string.

# Close the multiline string on the same line

Make sure to close the multiline string on the same line.

main.py
multiline_str = """\ first second third""" # ๐Ÿ‘ˆ๏ธ close on same line print(multiline_str)
The code for this article is available on GitHub

If you don't close the multiline string on the same line, an extra newline character gets added at the end of the string.

# Ident or dedent the multiline string

You can use the textwrap.indent() and textwrap.dedent() methods to indent or dedent the multiline string.
main.py
from textwrap import dedent, indent multiline_str = """\ first second third""" # ๐Ÿ‘‡๏ธ without indentation # first # second # third print(dedent(multiline_str)) # ๐Ÿ‘‡๏ธ indent the multiline string a specific number of spaces # first # second # third print(indent(multiline_str, ' '))

The textwrap.dedent() method takes a multiline string and removes the common leading whitespace from every line of the string.

The method is used to display multiline strings that are indented in the source code without any indentation.

The textwrap.indent() method takes a multiline string and a prefix and adds the prefix to the beginning of each line of the string.

By default, the method adds the prefix to the beginning of each line that doesn't consist only of whitespace.

# Remove the empty lines at the beginning and end of the multiline string

You can also use the inspect.cleandoc method if you want to remove the empty lines at the beginning and end of the multiline string and the leading whitespace.

main.py
from inspect import cleandoc multiline_str = """ first second third """ # # first # second # third # print(multiline_str) # first # second # third print(cleandoc(multiline_str))
The code for this article is available on GitHub

I intentionally didn't add a backslash at the end of the first line and didn't close the multiline string on the same line.

Notice that the inspect.cleandoc() method removed the empty lines at the beginning and end of the string and removed the leading whitespace.

If you don't want to remove the empty lines at the beginning and end of the multiline string, use the textwrap.dedent() method.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev