New Lines and Escape Characters

Printing + Comments

New Lines and Escape Characters

In this tutorial, we'll control line breaks, tabs, and quotes inside strings.

Sometimes you want a string to contain something that is hard to type directly, such as a new line, a tab, or a quote mark inside quotes. Python uses escape characters for this.

An escape character starts with a backslash: \.

New Lines

Use \n to add a new line inside a string:

print("Line one\nLine two")

Output:

Line one
Line two

This is useful for short multi-line messages:

print("Receipt\nApples: 2\nBread: 1")

Tabs

Use \t to add a tab space:

print("Name\tScore")
print("Ada\t95")
print("Ben\t82")

Output:

Name    Score
Ada     95
Ben     82

Tabs can help line up simple output, though for professional formatting you will later learn more powerful tools.

Quotes Inside Strings

If your string uses double quotes, you can escape a double quote inside it:

print("She said \"hello\"")

Output:

She said "hello"

You can also avoid escaping by using single quotes outside:

print('She said "hello"')

Both approaches are valid.

Backslashes

To print a real backslash, use two backslashes:

print("C:\\Users\\Sam")

Practice

Print a small menu with a title on the first line and three options on separate lines.