Python: Insert New Line into String

To insert a newline into a string in Python, use the \n keyword or use multi-line strings. In this tutorial, we will learn how to use both methods.

 

Insert NewLine into Python String Using \n

Put \n anywhere in the string where a newline should be. Here is an example:

 

foo = 'Hello\nworld'

print(foo)
Hello
world

 

Insert Newlines in Python Using Multi-line Strings

Multi-line strings allow the contents to be on multiple lines within the code. To open a multi-line string use """ (three speech marks) and close it using the same. Here is an example:

 

string = """hello this is a line
and this is a line
and another line
"""

print(string)
hello this is a line
and this is a line
and another line

 

Python String Line Breaks on Windows and Linux Using os.linesep

If your program will run on both Windows and Linux, consider using the linesep function from the os package to create new lines in strings. Here is an example of how to use it:

 

import os

foo = f'Hello{os.linesep}world'

print(foo)
Hello
world