Python Escape Characters
👉Python Escape Character Sequences with Examples
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.
👉Syntax of Escape Sequences
Python Escape Characters
python
CopyEdit
\EscapeCharacter
Here, the backslash (\) is followed by a character like n, t, or b to perform various actions.
👉Types of Python Escape Characters
Python offers various escape sequences for different purposes:
Code | Description |
\’ | Single quotation mark |
\\ | Backslash |
\n | New Line |
\r | Carriage Return |
\t | Horizontal Tab |
\b | Backspace |
\f | Form Feed |
\ooo | Octal Value |
\xhh | Hexadecimal Value |
👉Example Usage of Escape Characters
Here’s how each escape sequence works with examples:
- New Line (\n)
python
txt = “Software Moji\nMoji!”
print(txt)
Output:
nginx
Software Moji
Moji!
- Backslash (\\)
python
txt = “Software Moji\\Moji!”
print(txt)
Output:
nginx
Software Moji\Moji!
- Hexadecimal Value (\xhh)
python
txt = “\x47\x75\x72\x75 Moji!”
print(txt)
Output:
nginx
Guru Moji!
- Octal Value (\ooo)
python
txt = ‘\107\125\122\125 Moji!’
print(txt)
Output:
nginx
GURU Moji!
- Backspace (\b)
python
txt = “Software Moji\bMoji!”
print(txt)
Output:
nginx
Software MojiMoji!
- Form Feed (\f)
python
txt = “Software Moji\fMoji!”
print(txt)
Output:
nginx
Software Moji
Moji!
- Carriage Return (\r)
python
txt = “Software Moji\rMoji!”
print(txt)
Output:
Moji!
- Single Quotation (\’)
python
txt = “Software Moji\’Moji!”
print(txt)
Output:
rust
Software Moji’Moji!
👉What Does \t Do in Python?
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.
👉Using chr() and ord() for Tabs
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
👉Summary
✅ 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.