Table of contents
1.
Introduction 
2.
List of Escape Sequences Available in Python with Examples
3.
How to Escape Single Quotes in Python?
3.1.
1. n Escape Sequence in Python
3.2.
Python
3.3.
2. Python escape sequence for Space
3.4.
Python
3.5.
3. Backslash Escape Sequence in Python
3.6.
Python
3.7.
Python
3.8.
4. Backspace Escape Sequence in Python
3.9.
Python
3.10.
5. Python escape sequence for Hexa value
3.11.
Python
3.12.
6. Python escape sequence for Octal value
3.13.
Python
3.14.
7. Remove all escape sequences from a list
3.15.
Python
3.16.
8. Python escape sequence ignore
3.17.
Python
3.18.
9. Python escape sequence remove
3.19.
Python
3.20.
10. Escape Sequence Interpretation
3.21.
Python
4.
Preventing Escape Sequence Interpretation
4.1.
Python
5.
Escape Sequence Interpretation
5.1.
Python
6.
Methods of Prevention
6.1.
Raw String Literal
6.2.
Python
6.3.
Double Backslashes
6.4.
Python
7.
Frequently Asked Questions
7.1.
What is escape in string?
7.2.
Which is the escape sequence?
7.3.
How do you remove escape sequences from a string?
7.4.
What happens if an unsupported escape sequence is used?
7.5.
What is the size of an escape sequence in Python?
8.
Conclusion
Last Updated: Jan 29, 2025
Easy

Escape Sequences in Python

Author Tashmit
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction 

A sequence is an ordered collection of elements, where the order of the elements matters. The elements within a sequence can be integers, characters, strings, lists, or other types of sequences.

Escape Sequences in Python

An escape sequence is a sequence of characters that, when included within a character or string, doesn't directly represent itself. Instead, it's transformed into a different character or set of characters.

List of Escape Sequences Available in Python with Examples

Escape CharacterMeaningExample
\’Single quoteprint('It\'s a great day!')
\\’Double quoteprint("This is a \"quote\".")
\\Prints a backslashprint('This \\ is a backslash.')
\nNewlineprint('This \n is a new line.')
\rCarriage Returnprint('Hello\rWorld') (Hello will be overwritten by World)
\tHorizontal Tabprint('This \t is a tab.')
\bBackspaceprint('Hello\bWorld')
\fFormfeedprint('Hello\fWorld')
\vVertical Tabprint('Hello\vWorld')
\0Null Characterprint('Hello\0World') (The null character terminates the string)
\"\N{Name}Unicode character Database named lookupprint('This \" is a double quote.')
\\\uxxxxxxxxUnicode character with a 16-bit hex valueprint('This \\ is a backslash.')
\UxxxxxxxxUnicode character with a 32-bit hex valueprint('\U0001F600') (Displays a smiling face emoji)
\000Character with octal value oooprint('\000') (Null character in octal)
\xhhPrints the characters using their hexadecimal valueprint('\x48\x65\x6c\x6c\x6f') (Prints "Hello")

How to Escape Single Quotes in Python?

Escape sequences are widely used in programming languages to manipulate strings and characters in various ways. The most used escape sequences are:

1. n Escape Sequence in Python

The \n escape sequence is used to insert a new line in the code. For example,

Code

  • Python

Python

print("Welcome to \nCoding Ninjas")
You can also try this code with Online Python Compiler
Run Code


Output

Welcome to 
Coding Ninjas

2. Python escape sequence for Space

The \t escape sequence is used to add tab space(8 spaces) wherever required. For example,

Code

  • Python

Python

print("Name\tAge\Language")
print("Cody\t25\tC++")
print("Jack\t31\tPython")
You can also try this code with Online Python Compiler
Run Code


Output

Name   Age   Language
Cody   25      C++
Jack   31      Python

3. Backslash Escape Sequence in Python

The backslash escape sequence is used to print a backslash in our code. If we want to print a backslash using a simple print statement, it will give an error message:

  • Python

Python

print("\")
You can also try this code with Online Python Compiler
Run Code

 

This statement would produce an error message 

File “<ipython-input-3-dff1232de400>”, line 1
    print("\")
             ^
SyntaxError: EOL while scanning string literal

Therefore, to print a backslash, we would have to use an escape sequence like:

Code

  • Python

Python

print("Coding ninjas path: C:\\Windows\\Desktop\\Coding_Ninjas")
You can also try this code with Online Python Compiler
Run Code


The above code will be able to print the backslash in this code 

Output

Coding ninjas path: C:\Windows\Desktop\Coding_Ninjas

4. Backspace Escape Sequence in Python

In Python, the backspace escape sequence is defined by the character combination "\b." This sequence moves the cursor from one position to the left, effectively erasing the character before it.

Code

  • Python

Python

print("Hello\bWorld")
print("Hello \bWorld")
You can also try this code with Online Python Compiler
Run Code

Output

HelloWorld
HelloWorld

5. Python escape sequence for Hexa value

In Python, the escape sequence \x, followed by the hexadecimal digit, is used to represent a character using its hexadecimal value.

Code

  • Python

Python

print('\x48\x65\x6c\x6c\x6f') 
You can also try this code with Online Python Compiler
Run Code

Output

Hello

6. Python escape sequence for Octal value

In Python, the octal value of a character can be defined with the help of the escape sequence \ followed by up to three octal digits.

Code

  • Python

Python

print('\156\151\156\152\141')
You can also try this code with Online Python Compiler
Run Code

Output

ninja

7. Remove all escape sequences from a list

You can remove escape sequences from a string in Python by using the re-module (regular expressions) to match and remove them. 

Code

  • Python

Python

import re
string_with_Escape = "Hello\\n\\tNinja"
escSeq_removed = re.sub(r'\\.', '', string_with_Escape)

print(escSeq_removed)
You can also try this code with Online Python Compiler
Run Code

Output

HelloNinja

8. Python escape sequence ignore

In Python, if you want to ignore the escape sequences in a string, you can use a raw string by prefixing it with the letter "r". This is also known as a raw string literal.

Code

  • Python

Python

string_WithEscape = "Hello\nNinja"
string_IgnoreEscape = r"Hello\nNinja"

print(string_WithEscape)
print(string_IgnoreEscape)
You can also try this code with Online Python Compiler
Run Code

Output

Hello
Ninja
Hello\nNinja

9. Python escape sequence remove

To remove escape sequences from a string in Python, we can use the encode and decode methods with the "unicode_escape" encoding and then replace the escaped backslashes with regular backslashes. 

Code

  • Python

Python

string_with_escapeSeq = "Hello\\nWorld\\t"
escape_removed = string_with_escapeSeq.encode().decode('unicode_escape').replace('\\', '')
print(escape_removed) 
You can also try this code with Online Python Compiler
Run Code

Output

Hello
World

10. Escape Sequence Interpretation

Escape Sequence Interpretation is understanding the escape sequences defined in a string. When an escape sequence is encountered in a string, it is interpreted and replaced by a special character or action. For example, the escape sequence \n is used to add a newline character, and \t is used to add a tab character.

With the help of string literals, programmers can use escape sequences that are rather difficult to implement in their programs. When the computer reads a string containing escape sequences, Python interprets them and transforms them accordingly.

Code

  • Python

Python

print("Hello\nWorld")
You can also try this code with Online Python Compiler
Run Code

Output

Hello
World

 

Explanation 

The string "Hello\nWorld" contains the \n escape sequence, which is interpreted as a newline character. When the string is printed, the newline character causes the text to move to the next line:

Preventing Escape Sequence Interpretation

 The double backslash (\\) can be used to represent a single backslash in your strings. This prevents escape sequence interpretation altogether in Python and treats backslashes as regular characters without any special meaning. This is known as escaping the backslash itself.

Code

  • Python

Python

string_with_escape = "This\\tis a\\nstring"
regex_with_escape = "\\n{2}-\\n{2}-\\n{4}"

print(string_with_escape) 
print(regex_with_escape)
You can also try this code with Online Python Compiler
Run Code


Output

This\tis a\nstring
\n{2}-\n{2}-n{4}

Escape Sequence Interpretation

Escape sequences in Python are used to represent characters that cannot be directly typed or to include special characters within strings. These sequences begin with a backslash (\) followed by a character that signifies a particular action or symbol, such as a newline (\n), tab (\t), or backslash (\\). They help format strings and represent characters like quotes, which would otherwise terminate a string. For example, \n moves the cursor to a new line, while \t inserts a tab space.

Here’s a code example demonstrating escape sequences:

  • Python

Python

text = "Hello,\nThis is a new line.\n\tThis is indented."
print(text)
You can also try this code with Online Python Compiler
Run Code

Output:

Hello,
This is a new line.
    This is indented.

In the above example, \n creates new lines, and \t adds a tab space. Escape sequences enhance string formatting and enable representation of special characters that cannot be typed directly.

Methods of Prevention

To prevent the interpretation of escape sequences in Python strings, the following methods can be followed:

Raw String Literal

By prefixing the string with the letter "r," we can create a raw string literal. This tells Python to treat the string as plain text without interpreting any escape sequences. 

Example:

Code

  • Python

Python

raw_string = r"Hello\nNinja"
print(raw_string)
You can also try this code with Online Python Compiler
Run Code

 

Output

Hello\nNinja

Double Backslashes

We can also use double backslashes (\\) to represent a literal backslash in the string. The first backslash escapes the second backslash, resulting in a single backslash character. This way, escape sequences are not interpreted. 

Example:

Code

  • Python

Python

string = "Welcome\\nNinja"
print(string)
You can also try this code with Online Python Compiler
Run Code

 

Output

Welcome\nNinja

Frequently Asked Questions

What is escape in string?

An escape character is a Python string is usually used for representing characters that can cause ambiguity during interpretation.

Which is the escape sequence?

An escape sequence includes a backslash () followed by an escape sequence character, octal number, or hexadecimal number.

How do you remove escape sequences from a string?

In Python, we can print a string as plain text without escape character interpretation by prefixing it with the letter "r".

What happens if an unsupported escape sequence is used?

If an unsupported escape sequence is used, it may result in a compiler or runtime error, or the sequence may be interpreted as regular text characters.

What is the size of an escape sequence in Python?

In Python, the size of an escape sequence is one. Regardless of the number of characters used to represent the escape sequence, it is treated as a single character. For example, the size of the escape sequence \n is 1.

Conclusion

Escape sequences in Python provide a powerful mechanism to handle special characters within strings, allowing for greater flexibility and control when working with text. By using escape sequences like newline (\n), tab (\t), and others, developers can format strings more efficiently and create more readable and dynamic outputs.

Recommended Readings:

Live masterclass