How to add a new line in python – 5 Simple Ways to Add a Newline Character in Python

How to add a new line in python: In this post, let us see, how to add a newline character to the output of the data to be printed in Python(\n).

1)In a multiline string, Add a newline character.

Newline character in python: Python Multiline String is a convenient way to represent multiple strings in an aligned format. As demonstrated below, a newline(n) character can be inserted to a multiline string–

Syntax:

string = '''str_1\nstr_2....\nstr_N'''

In a multiline string, ‘\n’ before every string means to display on a new line.

Example

# Give the string as static input and store it in a variable.
gvn_str = '''good morning btechgeeks\nhello this is\nbtechgeeks'''
# Print the given string
print(gvn_str)

Output:

good morning btechgeeks
hello this is
btechgeeks

2)Add a newline to a List in Python

How to add new line in python: Python List can be thought of as a dynamic array that stores heterogeneous elements at runtime.

The string.join() function can be used to insert a new line between the list’s members.

Syntax:

'\n'.join(list)

Example

# Give the list as static input and store it in a variable.
gvn_lst = ['hello', 'this', 'is', 'btechgeeks']
# Print the given list
print("The given original list = ", gvn_lst)
# Pass the given list as an argument to the join() function
# and pass the delimiter as '\n'
gvn_lst = '\n'.join(gvn_lst)
# print the given list after adding a newline character to the given list
print("After adding a newline character to the given list:\n", gvn_lst)

Output:

The given original list =  ['hello', 'this', 'is', 'btechgeeks']
After adding a newline character to the given list:
 hello
this
is
btechgeeks

3)To Display a New line on the Console

New line character in python: At the very start, it is essential to understand how to execute functions on the console.

Use the following code to add a new line into the console:

print("string_1\nstring_2")

Example:

print("hello\nbtechgeeks")

Output:

hello
btechgeeks

4)To Display a Newline using Print Statement

New line character python: As illustrated below, the newline character can be added to the print() function to display the string on a new line.

Syntax:

print("string_1\nstring_2\n..........\string_N")

Example:

print("good morning btechgeeks")
print("print() hello this is btechgeeks")
print("welcome to\nbtechgeeks")

Output:

good morning btechgeeks
print() hello this is btechgeeks
welcome to
btechgeeks

5)To Add a Newline character using f-string in Python

Python newline character: The f-string in python represents the string statements in a formatted manner on the console.

To insert or add a newline character into an f-string, use the following syntax:

Syntax:

newline = '\n'
string = f"str_1{newline}str_2"

Example:

newline = '\n'
gvn_str = f"hello{newline}this{newline}is{newline}btechgeeks"
print(gvn_str)

Output:

hello
this
is
btechgeeks