In Python, escape characters are used when we need to include special characters in a string that are otherwise hard (or illegal) to type directly. These are preceded by a backslash (\), which tells Python that the next character is going to be a special character. They’re especially helpful for:
- Formatting strings (adding tabs, newlines)
- Including quotes inside quotes
- Writing file paths
- Inserting control characters
Here’s a breakdown of commonly used escape characters in Python:
| Escape Character | Description |
|---|---|
| \n | Newline – Moves the cursor to the next line. |
| \t | Tab – Adds a horizontal tab. |
| \\ | Backslash – Inserts a literal backslash. |
| \' | Single Quote – Inserts a single quote inside a single-quoted string. |
| \" | Double Quote – Inserts a double quote inside a double-quoted string. |
| \r | Carriage Return – Moves the cursor to the beginning of the line. |
| \b | Backspace – Moves the cursor one position back, effectively deleting the last character. |
| \f | Form Feed – Moves the cursor to the next page. |
| \v | Vertical Tab – Moves the cursor vertically. |
| \xhh | Hexadecimal – Represents a character using hexadecimal value hh. |
Detailed Explanation with Examples
1. \n (Newline)
Breaks the string into a new line.
print("Hello, World!\nWelcome to Python.")
Output
Hello, World! Welcome to Python.
2. \t (Tab)
The \t escape character inserts a tab space between words or characters.
print("Name\tAge\tLocation")
Output
Name Age Location
3. \\ (Backslash)
The \\ escape character inserts a literal backslash in the string.
print("This is a backslash: \\")
Output
This is a backslash: \
4. \' (Single Quote)
The \' escape character allows you to insert a single quote within a string that is enclosed by single quotes.
print('It\'s a great day!')
Output
It's a great day!
5. \" (Double Quote)
The \" escape character allows you to insert a double quote within a string that is enclosed by double quotes.
print("He said, \"Hello!\"")
Output
He said, "Hello!"
6. \r (Carriage Return)
The \r escape character moves the cursor to the beginning of the line. It can overwrite the existing text.
print("Hello, World!\rHi")
Output
Hello, World! Hi
7. \b (Backspace)
The \b escape character moves the cursor one character back, effectively deleting the last character.
print("Hello, World!\b")
Output
Hello, World!
8. \f (Form Feed)
The \f escape character moves the cursor to the next page (less commonly used in modern programming).
print("Hello\fWorld!")
Output
HelloWorld!
9. \v (Vertical Tab)
The \v escape character moves the cursor vertically (less commonly used).
print("Hello\vWorld!")
Output
HelloWorld!
10. \xhh (Hexadecimal)
The \xhh escape character represents a character using its hexadecimal value hh.
# Define a string with hexadecimal escape sequences
print("Hello \x48\x65\x6C\x6C\x6F")
Output
Hello Hello