Escape Characters

Escape characters in Python are used to insert special characters into strings that are otherwise difficult or impossible to write directly.
They start with a backslash (\) followed by a character.

What Are Escape Characters?

Escape characters allow you to:
  • Add new lines
  • Insert tabs
  • Include quotes inside strings
  • Represent special characters
Definition

An escape character is a backslash followed by a character that has a special meaning in a string.


New Line (\n)

The \n escape character creates a new line in the output.
python
print("Hello\nWorld")
python
print("Python\nis\nawesome")
python
text = "Line1\nLine2\nLine3"
print(text)

Tab (\t)

The \t escape character inserts a tab space.
python
print("Python\tProgramming")
python
print("Name\tAge")
print("John\t25")
python
print("A\tB\tC")

Backslash (\\)

To print a backslash, you must escape it using another backslash.
python
print("C:\\Users\\Admin")
python
print("This is a backslash: \\")
python
path = "D:\\Python\\Files"
print(path)

Single Quote (\')

Used to include a single quote inside a single-quoted string.
python
print('It\'s Python')
python
text = 'Python\'s syntax is easy'
print(text)
python
print('That\'s awesome')

Double Quote (\")

Used to include double quotes inside a double-quoted string.
python
print("He said \"Hello\"")
python
text = "Python is \"easy\" to learn"
print(text)
python
print("Welcome to \"Code Marathi\"")

Carriage Return (\r)

The \r escape character moves the cursor to the start of the line.
python
print("Hello\rWorld")
python
print("Python\rJava")
python
print("12345\rAB")

Backspace (\b)

The \b escape character removes the character before it.
python
print("Hello\bWorld")
python
print("Python\b3")
python
print("ABC\bD")

Form Feed (\f)

Used to insert a form feed (rarely used).
python
print("Hello\fWorld")
python
print("Python\fProgramming")
python
print("A\fB")

Raw Strings (r)

Raw strings ignore escape characters and treat them as normal text.
python
print(r"C:\Users\Admin")
python
print(r"Hello\nWorld")
python
print(r"\tPython")
Best Practice

Use raw strings when working with file paths and regular expressions.


Summary

  • Escape characters start with \
  • \n creates a new line
  • \t adds a tab space
  • \\ prints a backslash
  • \' and \" handle quotes
  • Raw strings ignore escape sequences

Exercise

  • Print text on multiple lines using \n
  • Print a Windows file path
  • Use raw string to avoid escape characters