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
source: string_line_break.py
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
source: string_line_break.py
With indent
Using triple quotes with indentation could insert unnecessary spaces, as demonstrated below.
s = ''' Line1 Line2 Line3 '''print(s)# # Line1# Line2# Line3#
source: string_line_break.py
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:
s = 'Line1\n'\ 'Line2\n'\ 'Line3'print(s)# Line1# Line2# Line3
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
source: string_line_break.py
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
source: string_line_break.py
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
source: string_line_break.py
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'
source: string_line_break.py
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']
source: string_line_break.py
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
source: string_line_break.py
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'
source: string_line_break.py
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
source: string_line_break.py
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'
source: string_line_break.py
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
source: string_line_break.py
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
source: string_line_break.py
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
source: string_line_break.py
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
source: string_line_break.py
Any string can be specified in end
.
print('a', end='-')print('b', end='-')print('c')# a-b-c
source: string_line_break.py
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.)