Handle line breaks (newlines) in strings in Python | note.nkmk.me (2024)

This article explains how to handle strings including line breaks (line feeds, new lines) in Python.

Contents

  • Create a string containing line breaks
    • Newline character \n (LF), \r\n (CR + LF)
    • Triple quote ''', """
    • With indent
  • Concatenate a list of strings on new lines
  • Split a string into a list by line breaks: splitlines()
  • Remove or replace line breaks
  • Output with print() without a trailing newline

Create a string containing line breaks

Newline character \n (LF), \r\n (CR + LF)

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

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

On Unix, including Mac, \n (LF) is often used, and on Windows, \r\n (CR + LF) is often used as a newline character. Some text editors allow you to select a newline character.

Triple quote ''', """

You can write a string including line breaks with triple quotes, either ''' or """.

  • Create a string in Python (single/double/triple quotes, str())
s = '''Line1Line2Line3'''print(s)# Line1# Line2# Line3

With indent

Using triple quotes with indentation could insert unnecessary spaces, as demonstrated below.

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

By enclosing each line in '' or "", adding a line break \n at the end, and using a backslash \ to continue the line, you can write the string as follows:

This approach uses a mechanism in which consecutive string literals are concatenated. See the following article for details:

  • Concatenate strings in Python (+ operator, join, etc.)

If you want to add indentation in the string, add a space to the string on each line.

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

Since you can freely break lines within parentheses (), you can also write the string inside them without using backslashes \.

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

If you want to align the beginning of a line, you can add a backslash \ to the first line of triple quotes.

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

Concatenate a list of strings on new lines

You can concatenate a list of strings into a single string with the string method join().

  • Concatenate strings in Python (+ operator, join, etc.)

By calling join() from a newline character, either \n or \r\n, each element will be concatenated on new lines.

l = ['Line1', 'Line2', 'Line3']s_n = '\n'.join(l)print(s_n)# Line1# Line2# Line3print(repr(s_n))# 'Line1\nLine2\nLine3's_rn = '\r\n'.join(l)print(s_rn)# Line1# Line2# Line3print(repr(s_rn))# 'Line1\r\nLine2\r\nLine3'

As shown in the example above, you can check the string with newline characters intact using the built-in function repr().

Split a string into a list by line breaks: splitlines()

You can split a string by line breaks into a list with the string method, splitlines().

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

In addition to \n and \r\n, the string is also split by other newline characters such as \v (line tabulation) or \f (form feed).

See also the following article for more information on splitlines().

  • Split a string in Python (delimiter, line break, regex, and more)

Remove or replace line breaks

Using splitlines() and join(), you can remove newline characters from a string or replace them with another string.

s = 'Line1\nLine2\r\nLine3'print(''.join(s.splitlines()))# Line1Line2Line3print(' '.join(s.splitlines()))# Line1 Line2 Line3print(','.join(s.splitlines()))# Line1,Line2,Line3

It is also possible to change the newline character all at once. Even if the newline character is mixed or unknown, you can split the string with splitlines() and then concatenate the lines with the desired character.

s_n = '\n'.join(s.splitlines())print(s_n)# Line1# Line2# Line3print(repr(s_n))# 'Line1\nLine2\nLine3'

Since splitlines() splits both \n (LF) and \r\n (CR + LF), as mentioned above, you don't have to worry about which newline character is used in the string.

You can also replace the newline character with replace().

  • Replace strings in Python (replace, translate, re.sub, re.subn)
s = 'Line1\nLine2\nLine3'print(s.replace('\n', ''))# Line1Line2Line3print(s.replace('\n', ','))# Line1,Line2,Line3

However, be aware that it will not work if the string contains a different newline character than expected.

s = 'Line1\nLine2\r\nLine3's_error = s.replace('\n', ',')print(s_error)# ,Line3Line2print(repr(s_error))# 'Line1,Line2\r,Line3's_error = s.replace('\r\n', ',')print(s_error)# Line1# Line2,Line3print(repr(s_error))# 'Line1\nLine2,Line3'

You can use replace() multiple times to replace various newline characters, but since \r\n contains \n, it may not work correctly if done in the wrong order. As mentioned above, using splitlines() and join() is a safer approach, as you don't have to worry about the specific line feed characters being used.

s = 'Line1\nLine2\r\nLine3'print(s.replace('\r\n', ',').replace('\n', ','))# Line1,Line2,Line3s_error = s.replace('\n', ',').replace('\r\n', ',')print(s_error)# ,Line3Line2print(repr(s_error))# 'Line1,Line2\r,Line3'print(','.join(s.splitlines()))# Line1,Line2,Line3

You can use rstrip() to remove trailing newline characters.

  • Remove a substring from a string in Python
s = 'aaa\n'print(s + 'bbb')# aaa# bbbprint(s.rstrip() + 'bbb')# aaabbb

Output with print() without a trailing newline

By default, print() adds a newline at the end. Therefore, if you execute print() continuously, each output result will be displayed with a line break.

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

This is because the default value of the end argument of print(), which specifies the string to be added at the end, is '\n'.

If the empty string '' is specified in end, a line break will not occur at the end.

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

Any string can be specified in end.

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

However, if you want to concatenate strings and output them, it's more straightforward to concatenate the original strings directly. See the following article.

  • Concatenate strings in Python (+ operator, join, etc.)
Handle line breaks (newlines) in strings in Python | note.nkmk.me (2024)
Top Articles
Latest Posts
Article information

Author: Terence Hammes MD

Last Updated:

Views: 5607

Rating: 4.9 / 5 (69 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Terence Hammes MD

Birthday: 1992-04-11

Address: Suite 408 9446 Mercy Mews, West Roxie, CT 04904

Phone: +50312511349175

Job: Product Consulting Liaison

Hobby: Jogging, Motor sports, Nordic skating, Jigsaw puzzles, Bird watching, Nordic skating, Sculpting

Introduction: My name is Terence Hammes MD, I am a inexpensive, energetic, jolly, faithful, cheerful, proud, rich person who loves writing and wants to share my knowledge and understanding with you.