Python Escape Characters
An escape character is a backslash pair that stands for one hard-to-type character. The pair \n stands for a new line.
Start a new line
The \n pair tells Python to break the line at that spot.
print("Line one\nLine two")Add a tab space
The \t pair jumps to the next tab stop, like the Tab key.
print("Name:\tAda")Show a backslash
One backslash starts an escape pair. So you write it twice to show one real backslash.
print("C:\\Users\\Ada")Quotes inside quotes
A backslash before a quote lets that quote sit inside the string.
print("She said \"Hello\"")
print('It\'s fine')Raw strings keep backslashes
A raw string starts with the letter r, so escape pairs stay as plain text inside it. Later courses use raw strings for file paths and patterns.
print(r"C:\new\test")Example
poem = "Roses are red,\n\tviolets are blue,\n\t\tPython is fun."
print(poem)Key points
- Escape character: a backslash pair that stands for one hard-to-type character
- Use \n for a new line and \t for a tab space
- Use \\ to show one real backslash in your text
- Use r before a string to make it a raw string, where backslash pairs stay as plain text
In this example, poem holds one string with three lines inside it. Each \n starts a new line. Each \t adds a tab space at the start of a line. The second line has one tab, and the third line has two. print shows the poem just as the escape pairs describe it.
Note
A pair like \d is not a real escape.
Python warns you about it and keeps both characters.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
Which escape pair starts a new line?