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.
Python
print("Hello, World!\nWelcome to Python.")
OutputHello, World!
Welcome to Python.
2. \t (Tab)
The \t escape character inserts a tab space between words or characters.
Python
print("Name\tAge\tLocation")
3. \\ (Backslash)
The \\ escape character inserts a literal backslash in the string.
Python
print("This is a backslash: \\")
OutputThis 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.
Python
print('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.
Python
print("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.
Python
print("Hello, World!\rHi")
7. \b (Backspace)
The \b escape character moves the cursor one character back, effectively deleting the last character.
Python
The \f escape character moves the cursor to the next page (less commonly used in modern programming).
Python
9. \v (Vertical Tab)
The \v escape character moves the cursor vertically (less commonly used).
Python
10. \xhh (Hexadecimal)
The \xhh escape character represents a character using its hexadecimal value hh.
Python
# Define a string with hexadecimal escape sequences
print("Hello \x48\x65\x6C\x6C\x6F")
Similar Reads
Interview Preparation
Practice @Geeksforgeeks
Data Structures
Algorithms
Programming Languages
Web Technologies
Computer Science Subjects
Data Science & ML
Tutorial Library
GATE CS