Python From Beginner to Advanced

0% completed

Previous
Next
Python - Escape Characters

Escape characters in Python are used to include special characters in strings that would otherwise be difficult or impossible to represent. They are prefixed with a backslash (\) and allow us to format text, insert special characters, or control string behavior.

Escape characters are useful when working with strings that contain quotes, newlines, tabs, or special symbols, making them essential for proper string formatting and manipulation.

Common Escape Characters

Here is a table of common escape characters in Python, each with a description and example:

Escape CharacterDescriptionExample UsageOutput
\\Backslash"This is a backslash \\\\"This is a backslash \
\'Single quote'It\'s a single quote'It's a single quote
\"Double quote"He said, \"Hello\""He said, "Hello"
\nNewline"First line\nSecond line"Prints on two lines
\tHorizontal tab"Column 1\tColumn 2"Column 1 Column 2
\rCarriage return (Moves cursor to start of line)"Hello\rWorld"World replaces Hello
\bBackspace (Deletes previous character)"ABC\b"AB
\fForm feed (New page effect in some systems)"Page\fNew page"Page + form feed effect
\oooCharacter with octal value ooo"\101" (A)A
\xhhCharacter with hex value hh"\x41" (A)A

Example 1: Using Escape Characters in a String

Python3
Python3

. . . .

Explanation:

  1. The \" escape sequence allows double quotes inside a string.
  2. \n creates a newline, so the second sentence starts on a new line.
  3. The output will print:
    She said, "Python is amazing!"
    Let's learn escape characters.
    

Escape characters in Python allow you to format strings efficiently and include special characters such as newlines, tabs, and quotes. They help in handling string formatting, improving readability, and ensuring compatibility with different text processing scenarios.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next