---Advertisement---

Python Escape Characters: Comprehensive Guide with Examples 2025

By Bhavani

Published On:

---Advertisement---

Python Escape Characters: In Python programming, escape characters are special characters used to include illegal or unprintable characters in a string. These sequences are preceded by a backslash (\) and enable specific formatting or control within text.

Python Escape Characters

python

CopyEdit

\EscapeCharacter

Here, the backslash (\) is followed by a character like n, t, or b to perform various actions.


Python offers various escape sequences for different purposes:

CodeDescription
\’Single quotation mark
\\Backslash
\nNew Line
\rCarriage Return
\tHorizontal Tab
\bBackspace
\fForm Feed
\oooOctal Value
\xhhHexadecimal Value

Here’s how each escape sequence works with examples:

  1. New Line (\n)

python

txt = “Software Moji\nMoji!”

print(txt)

Output:

nginx

Software Moji

Moji!

  1. Backslash (\\)

python

txt = “Software Moji\\Moji!”

print(txt)

Output:

nginx

Software Moji\Moji!

  1. Hexadecimal Value (\xhh)

python

txt = “\x47\x75\x72\x75 Moji!”

print(txt)

Output:

nginx

Guru Moji!

  1. Octal Value (\ooo)

python

txt = ‘\107\125\122\125 Moji!’

print(txt)

Output:

nginx

GURU Moji!

  1. Backspace (\b)

python

txt = “Software Moji\bMoji!”

print(txt)

Output:

nginx

Software MojiMoji!

  1. Form Feed (\f)

python

txt = “Software Moji\fMoji!”

print(txt)

Output:

nginx

Software Moji

Moji!

  1. Carriage Return (\r)

python

txt = “Software Moji\rMoji!”

print(txt)

Output:

Moji!

  1. Single Quotation (\’)

python

txt = “Software Moji\’Moji!”

print(txt)

Output:

rust

Software Moji’Moji!


The \t escape sequence inserts a horizontal tab (spacing) between text.

Example Using \t:

python

TextExample = “Software Moji\tMoji”

print(TextExample)

Output:

nginx

Software Moji    Moji

When to Use \t in Python:

  • Useful when aligning text output.
  • Helps to create organized tabulated data for better readability.

Python’s built-in chr() function can also substitute the \t escape sequence.

Example Using chr(9) as a Tab:

python

TextExample = “Software Moji” + chr(9) + “Moji”

print(TextExample)

Output:

nginx

Software Moji    Moji

Unicode Character for Tab:

python

print(“Unicode character for the tab is”, ord(‘\t’))

Output:

vbnet

Unicode character for the tab is 9


✅ Escape sequences in Python begin with a backslash (\).
✅ Popular escape characters include \n, \t, \b, \r, \f, \xhh, and \ooo.
✅ The \t escape sequence simplifies adding spaces precisely in text formatting.
✅ chr(9) can be an alternative for \t.
✅ Escape sequences are essential in Python for enhanced string manipulation and formatting.

Python Variables

---Advertisement---

Leave a Comment