How To Print A New Line In Python

What we are going to see through this article is we will see in detail How To Print A New Line In Python. When printing certain strings on the output console screen or adding content to files, people often have to keep the text on the new line.

A lot of people wonder how to add text to a new line. Well, there are many ways to specify a new line in different parts of Python.

How To Print A New Line In Python

How to Print a New Line in Python

For most of the purposes, the newline character \n can be used to specify a new line. You can put this character within Python Strings.

Print a New Line in Python using multiline string

string = '''str1\nstr2....\nstrN'''

The source code

str='''Hello all!! \nI am Programmer \nWelcome to the Codingdiksha Tutorial'''
print(str)

Output

This is a sample output for your reference.

Hello all!! 
I am Programmer 
Welcome to the Codingdiksha Tutorial

Print a New Line in Python using python list

Below, A python list method is used to print a new line in the python program. The syntax is:

'\n'.join(list)

The program code

lst = ['Python','Java','Kotlin','Cpp']
print("List before adding newline character to it:",lst)
lst = '\n'.join(lst)
print("List after adding newline character to it:\n",lst)

Output

The output will show below:

List before adding newline character to it: ['Python', 'Java', 'Kotlin', 'Cpp']
List after adding newline character to it:
 Python
Java
Kotlin

Print a New Line using print statement

Here, We have to use a print statement to print a new line in the below program. The syntax is:

print("str1\nstr2\n...\strN")

The source code

print("Hello Folks! Let us start learning.")
print("Statement after adding newline through print() function....")
print("Hello Folks!\nLet us start learning.")

Output

The print() function will help to display the result on the screen.

Hello Folks! Let us start learning.
Statement after adding newline through print() function....
Hello Folks!
Let us start learning.

Using python f-string

Instead of using the above three methods, We can use the f-string to execute a task in this program.

newline = '\n'
string = f"str1{newline}str2"

The program code

newline = '\n'
str = f"Python{newline}Java{newline}Cpp"
print(str)

Output

The output will be given below for your reference.

Python
Java
Cpp

Read Also: Polymorphism In Python

Using a file

Instead of using all the above methods, We will use the file method to do a task here.

file_object.write("\n")

The python code

import os 
file = "/Python.txt"
with open(file, 'a') as file: 
  file.write("\n")  

Output

The final output will show below for your reference.

Hello Programmers !!

Final Thoughts

What we learned through this article is How To Print A New Line In Python. Also if you have any doubts please leave a comment via the comment box. And we ask that you benefit everyone who shared this article with your friends.

Leave a Comment