Python – Escape Characters

Escape characters in Python let you include special characters in strings that would otherwise be hard to type directly — like quotes, new lines, tabs, or backslashes.

In this tutorial, you'll learn:

  • What escape characters are
  • Commonly used escape sequences
  • How to use them in real Python programs

What Are Escape Characters?

An escape character is a backslash (\) followed by a character. It tells Python to interpret the character differently.

Example:

txt = "He said, \"Python is awesome!\""
print(txt)
# Output: He said, "Python is awesome!"

The \" allows us to include quotes inside a string without causing a syntax error.

Common Python Escape Characters

Escape CodeDescriptionExample
\'Single quote'It\'s awesome'
\"Double quote"He said, \"Hi!\""
\\Backslash"This is a backslash: \\"
\nNew line"Hello\nWorld"
\tTab (horizontal)"Name:\tJohn"
\rCarriage return"Hello\rWorld"
\bBackspace"ABC\bD" → "ABD"
\fForm feed"Line1\fLine2"
\oooOctal value"\110\145\154\154\157"
\xhhHex value"\x48\x65\x6c\x6c\x6f"

 

Examples of Escape Characters in Action

1. Including Quotes Inside a String

text = "She said, \"Learn Python now!\""
print(text)

2. New Lines and Tabs

print("First Line\nSecond Line")  # Adds a newline
print("Name:\tJohn")              # Adds a tab

3. Backslash

print("C:\\Users\\John")  # Output: C:\Users\John

What if I Don’t Want Escaping?

Use a raw string by prefixing it with r — Python will ignore escape characters.

print(r"C:\Users\John")  # Output: C:\Users\John

This is especially useful in file paths, regular expressions, etc.

Summary

  • Escape characters help insert special characters into strings.
  • Prefix a string with r to make it "raw" (disable escaping).
  • Common sequences: \n (newline), \t (tab), \\ (backslash), \" (quote).