Newline in Python

The newline character (\n) is a unique character used to represent a line break in a string or a text file. When encountered in a string or used in output operations. it instructs the program to start a new line. The newline character is essential for formatting text and creating multi-line strings.

Syntax

print(“—-\—-“)

Example 1

The code in this line is a string. Its argument passed to the “print()” function. “\n” within the string is an escape sequence that represents a new line. So it ends that line and starts a new one, then it prints “World”. So now The end result is a given separated line.

Python




print("Hello\nWorld")


Output 

Hello
World

Example 2

In this code, the text within the parentheses is a string. ‘\n’ within a string is a special character sequence called an escape sequence. It generally represents a “new line” which shows Python starts with a new line.

Python




print("Hi\nhello")


Output

Hi
hello

difference between newline and carriage return in python

The newline and carriage return are two special characters used to control text’s display and formatting. Although they may appear similar they have distinct functionalities & serve different purposes. This article aims to provide a clear understanding of the difference between newline & carriage return in Python.

  • The newline character is represented by “\n” & it is used to create a new line in the string or file.
  • The carriage return character represented by “\r” moves the cursor to the beginning of the current line without advancing to the next line.

Similar Reads

Newline in Python

The newline character (\n) is a unique character used to represent a line break in a string or a text file. When encountered in a string or used in output operations. it instructs the program to start a new line. The newline character is essential for formatting text and creating multi-line strings....

Carriage return in Python

...

Difference between Newline Character and Carriage Return

...

FAQs on newline and carriage return in Python

The carriage return character (\r) is a special control character that originated from the early days of typewriters and teletype machines. It represents the action of moving the cursor or print head back to the beginning of the current line. When encountered in a string or used in output operations....

Contact Us