Escape Sequences in Python

Escape Sequences in Python

Escape sequences are special character combinations that represent other characters or actions in strings. Here’s a complete list of Python escape sequences with two examples for each:

1. \\ – Backslash

python

print("This is a backslash: \\")  # Output: This is a backslash: \
print("Path: C:\\Users\\Name")    # Output: Path: C:\Users\Name

2. \' – Single quote

python

print('It\'s a beautiful day')    # Output: It's a beautiful day
print('Don\'t stop learning')    # Output: Don't stop learning

3. \" – Double quote

python

print("She said, \"Hello!\"")     # Output: She said, "Hello!"
print("Quote: \"To be or not to be\"")  # Output: Quote: "To be or not to be"

4. \n – Newline

python

print("Line 1\nLine 2")           # Output: Line 1 (newline) Line 2
print("Name:\nJohn")              # Output: Name: (newline) John

5. \r – Carriage return

python

print("Hello\rWorld")             # Output: World (overwrites Hello)
print("123456\rABC")              # Output: ABC456

6. \t – Horizontal tab

python

print("Name:\tJohn")              # Output: Name:    John
print("Item\tPrice")              # Output: Item    Price

7. \b – Backspace

python

print("Hello\b World")            # Output: Hell World
print("123\b45")                  # Output: 1245

8. \f – Form feed

python

print("Page 1\fPage 2")           # Output: Page 1 (form feed) Page 2
print("Top\fBottom")              # Output: Top (form feed) Bottom

9. \ooo – Octal value

python

print("\110\145\154\154\157")    # Output: Hello
print("\101\102\103")             # Output: ABC

10. \xhh – Hex value

python

print("\x48\x65\x6c\x6c\x6f")    # Output: Hello
print("\x41\x42\x43")            # Output: ABC

11. \N{name} – Unicode character by name

python

print("\N{grinning face}")        # Output: 😀
print("\N{euro sign}")           # Output: €

12. \uhhhh – Unicode character (16-bit hex)

python

print("\u03A9")                  # Output: Ω (Greek capital omega)
print("\u00A9")                  # Output: © (Copyright symbol)

13. \Uhhhhhhhh – Unicode character (32-bit hex)

python

print("\U0001F600")              # Output: 😀 (Grinning face)
print("\U0001F4A9")              # Output: 💩 (Pile of poo)

Note: Some escape sequences (like \ooo\xhh\uhhhh, and \Uhhhhhhhh) require specific numeric values to produce valid characters.

1. \v – Vertical Tab

(Used for vertical spacing, though rarely used in modern applications)

python

print("First Line\vSecond Line")  
# Output:
# First Line
#      Second Line

python

print("Name:\vJohn")  
# Output:
# Name:
#      John

2. \a – ASCII Bell (Alert Sound)

(Triggers a system beep sound when printed)

python

print("\a")  # Produces a beep sound (if supported by the terminal)

python

print("Warning!\a")  # Displays "Warning!" and may trigger a beep

3. \0 – Null Character

(Represents a null byte, often used in binary data processing)

python

print("Hello\0World")  # Output: Hello World (null character is invisible)

python

data = "ABC\0DEF"  
print(data.split("\0"))  # Output: ['ABC', 'DEF']

4. Raw Strings (r prefix) – Ignores Escape Sequences

(Useful for regex, file paths, etc.)

python

print(r"C:\Users\Name")  # Output: C:\Users\Name (no escape interpretation)

python

print(r"Newline\nNotApplied")  # Output: Newline\nNotApplied

5. \ at End of Line – Line Continuation

(Allows splitting a long string into multiple lines)

python

long_str = "This is a very long string that \
spans multiple lines in code but not in output."
print(long_str)  # Output: Single line without breaks

python

query = "SELECT * FROM users \
WHERE age > 18 \
ORDER BY name;"
print(query)  # Output: Single-line SQL query

6. \ with Triple Quotes – Multi-line Strings

(Preserves formatting, including newlines)

python

print("""Line 1
Line 2
Line 3""")
# Output:
# Line 1
# Line 2
# Line 3

python

html = """<div>
    <p>Hello</p>
</div>"""
print(html)  # Output: Multi-line HTML

Bonus: Combining Escape Sequences

python

print("Tab\tNewline\nBell\a")  
# Output:
# Tab     Newline
# [Bell sound]

python

print("Unicode Smiley: \U0001F600")  # Output: 😀

Summary Table

Escape SequenceMeaningExample Usage
\vVertical Tab"Line1\vLine2"
\aBell/Alert Sound"Error\a"
\0Null Character"Text\0End"
r"..."Raw String (no escape)r"C:\path"
\ at EOLLine Continuation"Long \
String"
"""..."""Multi-line String"""Line1\nLine2"""

These escape sequences help format strings, handle special characters, and control output behavior in Python. Let me know if you need more details! 🚀

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *