Nearby lessons

59 of 159

Python - Escape Characters

📌 What You Will Learn
  • Understand what escape characters are and how they start with a backslash
  • Use \n for a new line and \t for a horizontal tab
  • Print double quotes inside strings using \"
  • Explore the full list of escape characters including \r, \b, \f, \v, \' and \\

Introduction

Escape characters are special characters used inside string literals.

They start with a backslash (\) and give a special meaning to the next character.

Escape characters help us print special symbols, create new lines, insert tabs, and perform other formatting operations.

What are Escape Characters?

In Python, escape characters are used inside strings to perform special actions.

Each escape character begins with a backslash (\).

For example, \n creates a new line and \t inserts a horizontal tab.

Example 1 - New Line (\n)

🐍Code Cell
1s = "durga\nsoftware"
2 
3print(s)
Output
durga
software

Explanation

The \n escape character moves the cursor to the next line.

Everything after \n is printed on a new line.

Example 2 - Horizontal Tab (\t)

🐍Code Cell
1s = "durga\tsoftware"
2 
3print(s)
Output
durga	software

Explanation

The \t escape character inserts a horizontal tab space.

Example 3 - Using Double Quote Without Escape Character

🐍Code Cell
1s = "This is " symbol"
Output
File "", line 1
s = "This is " symbol"
                 ^
SyntaxError: invalid syntax

Explanation

Python treats the second double quote as the end of the string.

Therefore, the remaining text becomes invalid and causes a SyntaxError.

Example 4 - Using Double Quote With Escape Character

🐍Code Cell
1s = "This is \" symbol"
2 
3print(s)
Output
This is " symbol

Explanation

The \" escape character prints a double quote inside the string.

This allows us to include double quotes without ending the string.

Important Escape Characters

Escape Character Meaning
\n New Line
\t Horizontal Tab
\r Carriage Return
\b Back Space
\f Form Feed
\v Vertical Tab
\' Single Quote
\" Double Quote
\\ Backslash Symbol
📝 Key Takeaways
  • Escape characters start with a backslash and give special meaning to the next character
  • \n moves the cursor to a new line and \t inserts a horizontal tab
  • \" prints a double quote inside a string without ending it
  • Unescaped double quotes inside a string cause a SyntaxError
  • Common escapes include \r, \b, \f, \v, \' and \\

🧠 Test Your Knowledge

8 Questions
Progress: 0 / 8