Handle Line Breaks (Newlines) in Strings in Python

Modified: | Tags: Python, String

This article explains how to work with strings that contain line breaks (newlines) in Python.

Create Strings with Line Breaks

Newline Characters: \n (LF) and \r\n (CR + LF)

To insert a line break at a specific position in a string, use a newline character, either \n or \r\n.

s = 'Line1\nLine2\nLine3'
print(s)
# Line1
# Line2
# Line3

s = 'Line1\r\nLine2\r\nLine3'
print(s)
# Line1
# Line2
# Line3

On Unix-like systems, including macOS, \n (LF: Line Feed) is commonly used, while Windows typically uses \r\n (CR: Carriage Return + LF) as the newline character. Many text editors let you choose the newline character format.

Triple Quotes: ''' and """

You can also create multiline strings using triple quotes, either ''' or """.

s = '''Line1
Line2
Line3'''
print(s)
# Line1
# Line2
# Line3

Indentation

Using triple quotes with indentation may introduce unwanted spaces, as shown below:

s = '''
    Line1
    Line2
    Line3
    '''
print(s)
# 
#     Line1
#     Line2
#     Line3
#     

To avoid this, you can build the string line by line using individual string literals, ending each with \n, and placing a backslash \ at the end of each line for continuation:

s = 'Line1\n'\
    'Line2\n'\
    'Line3'
print(s)
# Line1
# Line2
# Line3

This works because consecutive string literals are automatically concatenated in Python. For more details, see the article below:

To include indentation within the string content, just add spaces at the start of each line:

s = 'Line1\n'\
    '    Line2\n'\
    '        Line3'
print(s)
# Line1
#     Line2
#         Line3

You can also use parentheses () to break lines instead of backslashes:

s = ('Line1\n'
     'Line2\n'
     'Line3')
print(s)
# Line1
# Line2
# Line3

s = ('Line1\n'
     '    Line2\n'
     '        Line3')
print(s)
# Line1
#     Line2
#         Line3

If you want to align the first line without adding a blank line at the top, prefix the triple-quoted string with a backslash:

s = '''\
Line1
Line2
Line3'''
print(s)
# Line1
# Line2
# Line3

s = '''\
Line1
    Line2
        Line3'''
print(s)
# Line1
#     Line2
#         Line3

Join a List of Strings with Line Breaks

You can combine a list of strings into a single string using the join() method.

By calling join() on a newline character (\n or \r\n), each list element is joined with a line break:

l = ['Line1', 'Line2', 'Line3']

s_n = '\n'.join(l)
print(s_n)
# Line1
# Line2
# Line3

print(repr(s_n))
# 'Line1\nLine2\nLine3'

s_rn = '\r\n'.join(l)
print(s_rn)
# Line1
# Line2
# Line3

print(repr(s_rn))
# 'Line1\r\nLine2\r\nLine3'

As shown above, you can use the built-in repr() function to view newline characters in their raw form.

Split a String by Line Breaks: splitlines()

To split a string into a list of lines, use the splitlines() method.

s = 'Line1\nLine2\r\nLine3'
print(s.splitlines())
# ['Line1', 'Line2', 'Line3']

In addition to \n and \r\n, splitlines() also handles other line separators like \v (vertical tab) and \f (form feed).

See the article below for more on splitlines():

Remove or Replace Line Breaks

You can remove or replace line breaks using a combination of splitlines() and join():

s = 'Line1\nLine2\r\nLine3'

print(''.join(s.splitlines()))
# Line1Line2Line3

print(' '.join(s.splitlines()))
# Line1 Line2 Line3

print(','.join(s.splitlines()))
# Line1,Line2,Line3

You can also normalize different types of newline characters into a single type. Even if a string contains mixed or unknown newline styles, you can split it with splitlines() and then rejoin it using your preferred character:

s_n = '\n'.join(s.splitlines())
print(s_n)
# Line1
# Line2
# Line3

print(repr(s_n))
# 'Line1\nLine2\nLine3'

Since splitlines() handles both \n and \r\n, you don’t need to worry about which one the string uses.

Alternatively, you can use the replace() method:

s = 'Line1\nLine2\nLine3'

print(s.replace('\n', ''))
# Line1Line2Line3

print(s.replace('\n', ','))
# Line1,Line2,Line3

However, be careful when working with mixed newline characters:

s = 'Line1\nLine2\r\nLine3'

s_error = s.replace('\n', ',')
print(s_error)
# ,Line3Line2

print(repr(s_error))
# 'Line1,Line2\r,Line3'

s_error = s.replace('\r\n', ',')
print(s_error)
# Line1
# Line2,Line3

print(repr(s_error))
# 'Line1\nLine2,Line3'

Since \r\n contains \n, replacing \n before \r\n may cause unexpected results. To handle mixed newlines reliably, use splitlines() followed by join():

s = 'Line1\nLine2\r\nLine3'

print(s.replace('\r\n', ',').replace('\n', ','))
# Line1,Line2,Line3

s_error = s.replace('\n', ',').replace('\r\n', ',')
print(s_error)
# ,Line3Line2

print(repr(s_error))
# 'Line1,Line2\r,Line3'

print(','.join(s.splitlines()))
# Line1,Line2,Line3

To remove only the trailing newline character, use the rstrip() method:

s = 'aaa\n'
print(s + 'bbb')
# aaa
# bbb

print(s.rstrip() + 'bbb')
# aaabbb

Use print() without a Trailing Newline

By default, the print() function adds a newline at the end of its output. So, printing multiple times will result in each item appearing on a new line:

print('a')
print('b')
print('c')
# a
# b
# c

This happens because the end parameter of print() defaults to '\n'.

To suppress the newline, set end='':

print('a', end='')
print('b', end='')
print('c', end='')
# abc

You can also specify any string as the ending character:

print('a', end='-')
print('b', end='-')
print('c')
# a-b-c

However, if you simply want to build a string, it's often clearer to concatenate it first, then print the result. See this article for more details:

Related Categories

Related Articles