How to Print a Newline in Python

In this tutorial, we will look at how to print newlines in Python and change the character that is at the end of a line.

 

Python Newline Statement Example

To print a new line in Python use \n (backslash n) keyword. When the code is rendered \n will become a newline. Here is an example of printing a string with a newline inside it:

 

print('hello \n world')
hello
 world

 

A thing to watch out for is Python will not automatically remove the leading whitespace on the newline. You can use \n without a space after and it will work:

 

print('hello \nworld')
hello
world

 

Newlines in Python f-strings

Newlines work in the same way with Python f-strings. Add \n wherever you need it to be:

 

print(f'{foo} \n {bar}')

 

Create Two Line Breaks in Python

To create more than one newline use multiple \n next to each other like this:

 

print('hello \n\nworld')
hello

world

 

The default behaviour of the Python print() statement is to put a newline (\n) at the end of a line. To print without newlines add the end= argument and set it to an empty string like this:

 

print('hello ', end='')
print('world')
hello world

 

Change the Newline Character in Python

You can change what is put at the end of each line by the Python print() statement using the end= argument. In the example below a space will be used instead of \n:

 

print('hello', end=' ')
print('world')
hello world