Table of Contents
ToggleAn escape character is a character followed by a backslash (\). It tells the interpreter that this escape sequence has a special meaning. For example, \n represents a newline. Python also supports raw strings, which ignore escape sequences. This guide explains escape characters and their usage in Python.
Escape characters are used to insert special characters or control sequences into strings. They are prefixed with a backslash (\) and are interpreted by Python to perform specific actions, such as creating a new line or inserting a tab.
In Python, a string becomes a raw string if it is prefixed with r or R before the quotation symbols. Raw strings ignore escape sequences and treat backslashes as literal characters.
# Normal string
normal = "Hello"
print(normal)
# Raw string
raw = r"Hello"
print(raw)
Output:
Hello
Hello
In normal circumstances, there is no difference between the two. However, when escape characters are embedded in the string, the normal string interprets the escape sequence, whereas the raw string does not.
normal = "Hello\nWorld"
print(normal)
raw = r"Hello\nWorld"
print(raw)
Output:
Hello
World
Hello\nWorld
The following table lists the most commonly used escape characters in Python:
| Sr.No | Escape Sequence | Meaning |
|---|---|---|
| 1 | \\ |
Backslash (\) |
| 2 | \' |
Single quote (') |
| 3 | \" |
Double quote (") |
| 4 | \a |
ASCII Bell (BEL) |
| 5 | \b |
ASCII Backspace (BS) |
| 6 | \f |
ASCII Formfeed (FF) |
| 7 | \n |
ASCII Linefeed (LF) |
| 8 | \r |
ASCII Carriage Return (CR) |
| 9 | \t |
ASCII Horizontal Tab (TAB) |
| 10 | \v |
ASCII Vertical Tab (VT) |
| 11 | \ooo |
Character with octal value ooo |
| 12 | \xhh |
Character with hex value hh |
The following code demonstrates the usage of various escape sequences:
# Ignore backslash and newline
s = 'This string will not include \
backslashes or newline characters.'
print(s)
# Escape backslash
s = 'The \\character is called backslash'
print(s)
# Escape single quote
s = 'Hello \'Python\''
print(s)
# Escape double quote
s = "Hello \"Python\""
print(s)
# Escape \b to generate ASCII backspace
s = 'Hel\blo'
print(s)
# ASCII Bell character
s = 'Hello\a'
print(s)
# Newline
s = 'Hello\nPython'
print(s)
# Horizontal tab
s = 'Hello\tPython'
print(s)
# Form feed
s = "hello\fworld"
print(s)
# Octal notation
s = "\101"
print(s)
# Hexadecimal notation
s = "\x41"
print(s)
Output:
This string will not include backslashes or newline characters.
The \character is called backslash
Hello 'Python'
Hello "Python"
Helo
Hello
Hello
Python
Hello Python
hello
world
A
A
Enroll in our Python certification course at Vista Academy and become a certified expert to boost your career.
Enroll Now