How do you break a line in a string in python?

This article describes how to handle strings including line breaks [line feeds, new lines] in Python.

  • Create a string containing line breaks
    • Newline code \n(LF), \r\n(CR + LF)
    • Triple quote ''' or """
    • 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 code \n(LF), \r\n(CR + LF)

Inserting a newline code \n, \r\n into a string will result in a line break at that location.

s = 'Line1\nLine2\nLine3'
print[s]
# Line1
# Line2
# Line3

s = '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 code. Some text editors allow you to select a newline code.

Triple quote ''', """

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

  • Create a string in Python [single, double, triple quotes, str[]]

s = '''Line1
Line2
Line3'''
print[s]
# Line1
# Line2
# Line3

With indent

If you use triple quotes and indent, as shown below, unnecessary spaces are inserted.

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 \, you can write as follows:

s = 'Line1\n'\
    'Line2\n'\
    'Line3'
print[s]
# Line1
# Line2
# Line3

It 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 in parentheses [], you can also write as follows using parentheses [] without using 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 just want to align the beginning of a line, you can add a backslash \ to the first line of triple quotes.

s = '''\
Line1
Line2
Line3'''
print[s]
# Line1
# Line2
# Line3

s = '''\
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 code \n or \r\n, each element is concatenated on new lines.

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 in the example above, you can check the string with newline codes intact with the built-in function repr[].

  • Built-in Functions - repr[] — Python 3.9.1rc1 documentation

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, it is also splitted by \v [line tabulation] or \f [form feed], etc.

  • Built-in Types - str.splitlines[] — Python 3.9.1rc1 documentation

See also the following article for more information on splitlines[].

  • Split strings in Python [delimiter, line break, regex, etc.]

Remove or replace line breaks

With splitlines[] and join[], you can remove newline codes from a string or replace them with another string.

s = 'Line1\nLine2\r\nLine3'

print[''.join[s.splitlines[]]]
# Line1Line2Line3

print[' '.join[s.splitlines[]]]
# Line1 Line2 Line3

print[','.join[s.splitlines[]]]
# Line1,Line2,Line3

It is also possible to change the newline code at once. Even if the newline code is mixed or unknown, you can split it with splitlines[] and then concatenate them with the desired code.

s_n = '\n'.join[s.splitlines[]]
print[s_n]
# Line1
# Line2
# Line3

print[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 code is used in the string.

You can also replace the newline code replace[].

  • Replace strings in Python [replace, translate, re.sub, re.subn]

s = 'Line1\nLine2\nLine3'

print[s.replace['\n', '']]
# Line1Line2Line3

print[s.replace['\n', ',']]
# Line1,Line2,Line3

However, note that it will not work if it contains a different newline code than expected.

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'

You can repeat replace[] to replace multiple newline codes, but because \r\n contains \n, it doesn't work well if you do it in the wrong order. As mentioned above, using splitlines[] and join[] is safe because you don't have to worry about line feed codes.

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

You can use rstrip[] to remove the trailing newline code.

  • Built-in Types - str.rstrip[] — Python 3.9.1rc1 documentation

s = 'aaa\n'
print[s + 'bbb']
# aaa
# bbb

print[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 argument end of print[], which specifies the character 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 the character strings and output, it is easier to concatenate the original character strings. See the following article.

  • Concatenate strings in Python [+ operator, join, etc.]

How do you break a single line in Python?

To break a line in Python, use the parentheses or explicit backslash[/]. Using parentheses, you can write over multiple lines. The preferred way of wrapping long lines is using Python's implied line continuation inside parentheses, brackets, and braces.

How do you break a line inside a string?

In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.

What does \r do in Python?

In Python strings, the backslash "\" is a special character, also called the "escape" character. It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a newline, and "\r" is a carriage return.

How do you cut a part of a string in Python?

Python has three built-in methods for trimming leading and trailing whitespace and characters from strings..
.strip[].
.lstrip[].
.rstrip[].

Chủ Đề