Python Escape Characters: \n, \t, Quotes and Raw Strings
An escape character is a backslash \ followed by a letter or symbol. It puts a special character, such as a new line or a quote, inside a string.
This lesson shows how to print text that has new lines, tabs or quotes in it. Read Printing Output first.
Start a new line with \n
\n is a new line. One print() can then show several lines.
print("Line one\nLine two\nLine three")
This prints three lines from one call.
Line up columns with \t
\t is a tab. It moves the text to the next tab stop, which lines up short columns.
print("Name\tScore")
print("Ada\t8")
print("Sam\t6")
Tabs line up only while every item is shorter than one tab stop, usually 8 characters.
Put quotes and backslashes inside a string
A quote that matches the string's own quotes ends the string. Escape it with \" or \', or use the other kind of quote outside.
print("She said \"hi\"")
print('It\'s ready')
print("It's ready")
print("C:\\games\\pig")
\\ prints one backslash. Without it, \g and \p are not valid escapes and Python warns.
Turn escapes off with a raw string
Put r before the quotes to make a raw string. Every backslash stays as it is.
print(r"C:\new\table")
print("C:\new\table")
The first line prints the path as typed. In the second, \n and \t become a new line and a tab.
Use a raw string when the backslashes are part of the text, such as a Windows path. Use escapes when you want the special characters.
Note: A raw string cannot end with a single backslash: r"C:\" is a syntax error.
See also: String Formatting, print() sep and end.
Your turn
Print the table below with one print() call. Use \t between the columns, \n between the lines and \" for the quotes.
# add one print with \t, \n and \" inside the string
Expected output
Name Score
"Ada" 8
"Sam" 6