Escape Characters
On this page
In Python, escape characters are backslash \
followed by the character you want to insert. This special sequence allows you to include particular string values that wouldn’t be possible to write directly.
Common Escape Characters
Here are some common escape characters used in Python:
\n
: Inserts a newline in the text at that point.\t
: Inserts a tab in the text at that point.\\
: Inserts a backslash character in the text at that point.\"
: Inserts a double quote character in the text at that point.\'
: Inserts a single quote character in the text at that point.
Let’s see these escape characters in action with some examples.
Running the above code outputs:
Raw Strings
Sometimes you might want to ignore the escape sequences in a string. This can be done using raw strings. Simply prefix your string with a r
or R
.
In the first print statement, \n
is treated as a newline. However, in the second print statement,
it’s treated as the literal characters ‘' and ’n’.
Running the above code outputs:
Note
The backslash \
followed by any character that doesn’t form a recognisable escape sequence results in a syntax error. Therefore, to include a literal backslash in a string, always escape it using \\
.