In Python (programming language), escape characters are special characters used inside strings to represent characters that are otherwise difficult to type directly.
Escape characters start with a backslash \.
They are commonly used to:
- Insert new lines
- Add tabs
- Include quotes inside strings
- Format text
1οΈβ£ New Line (\n)
Creates a new line in the output.
text = "Hello\nPython"
print(text)
Output
Hello
Python
2οΈβ£ Tab Space (\t)
Adds a tab space between text.
text = "Hello\tPython"
print(text)
Output
Hello Python
3οΈβ£ Backslash (\\)
Used to display a backslash character.
text = "This is a backslash \\"
print(text)
Output
This is a backslash \
4οΈβ£ Single Quote (\')
Used to include single quotes inside a string.
text = 'It\'s a good day'
print(text)
Output
It's a good day
5οΈβ£ Double Quote (\")
Used to include double quotes inside a string.
text = "He said \"Hello\""
print(text)
Output
He said "Hello"
6οΈβ£ Carriage Return (\r)
Moves the cursor to the beginning of the line.
text = "Hello\rPython"
print(text)
Output (Python overwrites the beginning)
Python
7οΈβ£ Backspace (\b)
Removes the previous character.
text = "Helloo\b" print(text)
Hello
β Example Program
print("Name:\tRahul")
print("Course:\tPython")
print("Message:\nWelcome to Python programming")
Output
Name: Rahul
Course: Python
Message:Welcome to Python programming
π Common Escape Characters
| Escape Character | Description |
|---|---|
\n | New line |
\t | Tab space |
\\ | Backslash |
\' | Single quote |
\" | Double quote |
\r | Carriage return |
\b | Backspace |
β Key Points
- Escape characters start with
\ - Used to format and control string output
- Helpful when working with file paths, text formatting, and quotes
Example:
print("C:\\Users\\Rahul\\Documents")
Output
C:\Users\Rahul\Documents