The newline escape sequence \n
is used in Python strings to insert a line break. When Python encounters \n
inside a string, it moves the cursor to the next line, effectively splitting the string output across multiple lines.
\n
# Example 1: Simple newline
print("Hello\nWorld")
# Output:
# Hello
# World
# Example 2: Multiple newlines
print("Line 1\nLine 2\nLine 3")
# Output:
# Line 1
# Line 2
# Line 3
# Example 3: Using newline in a variable
message = "First Line\nSecond Line"
print(message)
# Output:
# First Line
# Second Line
# Example 4: Combining newline with other text
print("Name:\nJohn Doe\nAge:\n30")
# Output:
# Name:
# John Doe
# Age:
# 30
# Example 5: Newline in multiline strings (triple quotes)
multiline_text = """This is line one.
This is line two.
This is line three."""
print(multiline_text)
# Output:
# This is line one.
# This is line two.
# This is line three.
The \n
escape sequence is essential for formatting string outputs in Python by introducing line breaks. It works both in single/double quoted strings and helps in making output readable and structured.