- Syntax
- Example 1: New Line (\n)
- Example 2: Horizontal Tab (\t)
- Example 3: Printing Double Quotes
- Example 4: Printing Single Quotes
- Example 5: Printing a Backslash
- Example 6: Multiple Escape Characters
- Example 7: Backspace (\b)
- Example 8: Carriage Return (\r)
- Example 9: User Input with Escape Characters
- Example 10: Combining Quotes and New Lines
- Common Mistakes
- Best Practices
- Key Points to Remember
Sometimes you need to include special characters inside a string, such as quotation marks, new lines, or tab spaces. Writing these characters directly may cause syntax errors or produce unintended output.
Python provides escape characters to represent special characters within strings.
An escape character begins with a backslash (\) followed by another character. Python interprets this combination as a special instruction instead of normal text.
Escape characters are commonly used for formatting text, displaying quotation marks, creating file paths, and improving output readability.
Syntax #
string_name = "Text with \escape_sequence"
Components #
| Component | Description |
|---|---|
\ |
Escape character (backslash). |
escape_sequence |
Character that specifies the special operation. |
Common Escape Characters #
| Escape Character | Description |
|---|---|
\n |
New line |
\t |
Horizontal tab |
\\ |
Backslash |
\' |
Single quotation mark |
\" |
Double quotation mark |
\b |
Backspace |
\r |
Carriage return |
Example 1: New Line (\n) #
main.py
print("Hello\nPython")
Output #
Hello
Python
Explanation #
\ninserts a new line.- Everything after
\nappears on the next line. - It is commonly used to print multiple lines with a single
print()statement.
Example 2: Horizontal Tab (\t) #
main.py
print("Name\tAge")
print("Alice\t21")
Output #
Name Age
Alice 21
Explanation #
\tinserts a horizontal tab.- It creates spacing between columns.
- The exact spacing depends on the terminal or editor.
Example 3: Printing Double Quotes #
main.py
print("He said, \"Hello!\"")
Output #
He said, "Hello!"
Explanation #
- The double quotes inside the string are escaped using
\". - Without the escape character, Python would think the string ends at the second quotation mark.
Example 4: Printing Single Quotes #
main.py
print('It\'s a beautiful day.')
Output #
It's a beautiful day.
Explanation #
- The apostrophe in
"It's"is escaped using\'. - This prevents Python from treating it as the end of the string.
Example 5: Printing a Backslash #
main.py
print("C:\\Users\\Alice")
Output #
C:\Users\Alice
Explanation #
- A single backslash begins an escape sequence.
- To print an actual backslash, use
\\. - This is commonly used for Windows file paths.
Example 6: Multiple Escape Characters #
main.py
print("Name\tAge\nAlice\t21")
Output #
Name Age
Alice 21
Explanation #
\tcreates spacing between columns.\nmoves the output to the next line.- Multiple escape characters can be combined in one string.
Example 7: Backspace (\b) #
main.py
print("ABC\bD")
Output #
ABD
Explanation #
\bmoves the cursor one position backward.- The character
Cis effectively overwritten byD. - The displayed result becomes
"ABD".
Note: The exact behavior of
\bmay vary depending on the terminal or console being used.
Example 8: Carriage Return (\r) #
main.py
print("Hello\rHi")
Output #
Hillo
Explanation #
\rmoves the cursor to the beginning of the current line.- The characters following
\roverwrite the existing characters from the start. - Here,
"Hi"replaces the first two characters of"Hello".
Note: The behavior of
\rcan vary slightly depending on the operating system and terminal.
Example 9: User Input with Escape Characters #
main.py
name = input("Enter your name: ")
print("Hello,\n" + name)
Sample Input #
Alice
Output #
Hello,
Alice
Explanation #
- The user enters a name.
\nprints the greeting and the name on separate lines.- The input string is concatenated with the formatted text.
Example 10: Combining Quotes and New Lines #
main.py
print("\"Python\" is\nawesome!")
Output #
"Python" is
awesome!
Explanation #
\"prints double quotation marks.\nmoves the remaining text to the next line.- Multiple escape sequences can be used together.
Common Mistakes #
1. Forgetting to Escape Quotes #
Incorrect
print("He said, "Hello!"")
Output #
SyntaxError: invalid syntax
Reason
The inner quotation marks terminate the string prematurely.
Correct
print("He said, \"Hello!\"")
2. Using a Single Backslash #
Incorrect
print("C:\Users\Alice")
Output #
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes...
Reason
The backslash begins an escape sequence.
Correct
print("C:\\Users\\Alice")
3. Assuming \n Prints the Characters \ and n #
Incorrect
print("Hello\nWorld")
Incorrect Expectation #
Hello\nWorld
Actual Output #
Hello
World
Reason
\n is interpreted as a newline character.
4. Expecting \t to Insert a Fixed Number of Spaces #
Incorrect
print("A\tB")
Incorrect Expectation #
A B
Reason #
A tab moves the cursor to the next tab stop, not a fixed number of spaces. The displayed spacing depends on the terminal or editor.
Best Practices #
- Use escape characters to improve the readability of output.
- Escape quotation marks only when necessary.
- Use
\\when writing Windows file paths. - Use
\nfor multi-line output instead of multipleprint()statements when appropriate. - Consider using raw strings (covered in the next lesson) when working extensively with file paths or regular expressions.
Key Points to Remember #
- Escape characters begin with a backslash (
\). - They represent special characters inside strings.
\ncreates a new line.\tinserts a horizontal tab.\\prints a backslash.\"and\'print quotation marks.- Escape characters improve formatting and allow special characters to be included in strings.