Python Escape Characters

Understand how to use escape characters in Python to include special or illegal characters in strings. Learn how a backslash \ followed by a character can help you insert these characters into your strings.



Python - Escape Characters

Escape Character

To insert characters that are illegal in a string, use an escape character.

An escape character is a backslash \ followed by the character you want to insert.

Example

Example (with Syntax Error)

An example of an illegal character is a double quote inside a string that is surrounded by double quotes:


txt = "We are the so-called "Heroes" from the north.
Error Output:

File "demo_string_escape_error.py", line 1
    txt = "We are the so-called "Heroes" from the north."
                                       ^
SyntaxError: invalid syntax

To fix this problem, use the escape character \":

Example

The escape character allows you to use double quotes when you normally would not be allowed:

Example

      txt = "We are the so-called \"Heroes\" from the north."
      print(txt)
      
Output

      We are the so-called "Heroes" from the north.
      

Escape Characters

Other escape characters used in Python:

Code Result
\' Single Quote
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
\ooo Octal value
\xhh Hex value