- Handle line breaks (newlines) in strings in Python
- 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
- Related Categories
- Related Articles
- Python Strings: Learn How to Add Line Breaks
- Python Strings: Learn How to Add Line Breaks
- How to print a line break in Python
- Using line breaks in Python
- Conclusion
- How can I break up this long line in Python? [duplicate]
- 6 Answers 6
Handle line breaks (newlines) in strings in Python
This article explains how to handle strings including line breaks (line feeds, new lines) in Python.
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 # 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 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 «»» .
s = '''Line1 Line2 Line3''' 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:
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:
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 # Line3 s = ('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 = '''\ 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() .
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 # 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 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() .
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())) # Line1Line2Line3 print(' '.join(s.splitlines())) # Line1 Line2 Line3 print(','.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 # 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 character is used in the string.
You can also replace the newline character with replace() .
s = 'Line1\nLine2\nLine3' print(s.replace('\n', '')) # Line1Line2Line3 print(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) # ,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 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,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 trailing newline characters.
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 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.
Related Categories
Related Articles
- Right-justify, center, left-justify strings and numbers in Python
- Concatenate strings in Python (+ operator, join, etc.)
- Remove a part of a string (substring) in Python
- Split strings in Python (delimiter, line break, regex, etc.)
- Extract and replace elements that meet the conditions of a list of strings in Python
- Count characters and strings in Python
- Get the filename, directory, extension from a path string in Python
- How to use f-strings in Python
- Raw strings in Python
- Extract a substring from a string in Python (position, regex)
- Convert Unicode code point and character to each other (chr, ord)
- Wrap and truncate a string with textwrap in Python
- String comparison in Python (exact/partial match, etc.)
- Get the length of a string (number of characters) in Python
- Convert a string to a number (int, float) in Python
Python Strings: Learn How to Add Line Breaks
Python strings can be used to store text and data. They are useful for displaying text to users, writing messages, and other types of communication. In some cases, you may need to add a line break to your string. This article will explain how to do this in Python.
Python Strings: Learn How to Add Line Breaks
Python strings can be used to create sentences and phrases. Line breaks can be added to a string in order to create a new line, paragraph, or section in the text. There are several different methods that can be used to add line breaks to a Python string.
# method 1: Using «\n» character
In Python, you can use the newline character («\n») to add a line break to a string. Here is an example:
my_string = "Hello, World!\nGoodbye, World!" print(my_string) # Output: # Hello, World! # Goodbye, World!
You can also use triple quotes (»’ or «»») to create a multi-line string, which allows you to include line breaks in the string directly, without using the newline character:
my_string = '''Hello, World! Goodbye, World!''' print(my_string) # Output: # Hello, World! # Goodbye, World!
Alternatively, you can use the string concatenation operator (+) to combine multiple strings and add line breaks between them:
my_string = "Hello, World!\n" + "Goodbye, World!" print(my_string) # Output: # Hello, World! # Goodbye, World!
# method 3: Using f-strings
You can also use the f-strings feature introduced in Python 3.6 to insert line breaks into a string. Here is an example:
my_string = f"Hello, World!\nGoodbye, World!" print(my_string) # Output: # Hello, World! # Goodbye, World!
Note that the line breaks in the string will be visible when you print the string or write it to a file, but they will not be included in the string itself when you access it or manipulate it.
How to print a line break in Python
When you’re working with strings, knowing how to create a line break is very useful.
A line break allows you to define when a section of text should be broken into multiple lines.
Rather than printing text multiple times, each on a different line, you can define a single text string that contains line breaks.
In this post, we’ll look at how to use line breaks in Python.
Using line breaks in Python
The easiest way to use line breaks in Python is to use the \n character. This character indicates that the text that follows after it will be on a new line.
Simply include the \n character in your string when you want to break the text into multiple lines.
Here’s an example of a 3-line string:
Another useful way to use line breaks is when you’re in a loop.
Conclusion
In this post, we learned about how to use line breaks in Python.
To create a line break, simply include the \n character in your string.
Thanks for reading and happy coding!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
Give feedback on this page , tweet at us, or join our Discord !
How can I break up this long line in Python? [duplicate]
How would you go about formatting a long line such as this? I’d like to get it to no more than 80 characters wide:
logger.info("Skipping because its thumbnail was already in our system as .".format(line[indexes['url']], video.title))
url = "Skipping because its thumbnail was already in our system as ." logger.info(url.format(line[indexes['url']], video.title))
6 Answers 6
That’s a start. It’s not a bad practice to define your longer strings outside of the code that uses them. It’s a way to separate data and behavior. Your first option is to join string literals together implicitly by making them adjacent to one another:
("This is the first line of my text, " "which will be joined to a second.")
Or with line ending continuations, which is a little more fragile, as this works:
"This is the first line of my text, " \ "which will be joined to a second."
"This is the first line of my text, " \ "which will be joined to a second."
See the difference? No? Well you won’t when it’s your code either.
(There’s a space after \ in the second example.)
The downside to implicit joining is that it only works with string literals, not with strings taken from variables, so things can get a little more hairy when you refactor. Also, you can only interpolate formatting on the combined string as a whole.
Alternatively, you can join explicitly using the concatenation operator ( + ):
("This is the first line of my text, " + "which will be joined to a second.")
Explicit is better than implicit, as the zen of python says, but this creates three strings instead of one, and uses twice as much memory: there are the two you have written, plus one which is the two of them joined together, so you have to know when to ignore the zen. The upside is you can apply formatting to any of the substrings separately on each line, or to the whole lot from outside the parentheses.
Finally, you can use triple-quoted strings:
"""This is the first line of my text which will be joined to a second."""
This is often my favorite, though its behavior is slightly different as the newline and any leading whitespace on subsequent lines will show up in your final string. You can eliminate the newline with an escaping backslash.
"""This is the first line of my text \ which will be joined to a second."""
This has the same problem as the same technique above, in that correct code only differs from incorrect code by invisible whitespace.
Which one is «best» depends on your particular situation, but the answer is not simply aesthetic, but one of subtly different behaviors.