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

  • Python Modules: Creation and Usage Guide

    Python Modules: Creation and Usage Guide What are Modules in Python? Modules are simply Python files (with a .py extension) that contain Python code, including: They help you organize your code into logical units and promote code reusability. Creating a Module 1. Basic Module Creation Create a file named mymodule.py: python # mymodule.py def greet(name): return f”Hello, {name}!”…

  • re.I, re.S, re.X

    Python re Flags: re.I, re.S, re.X Explained Flags modify how regular expressions work. They’re used as optional parameters in re functions like re.search(), re.findall(), etc. 1. re.I or re.IGNORECASE Purpose: Makes the pattern matching case-insensitive Without re.I (Case-sensitive): python import re text = “Hello WORLD hello World” # Case-sensitive search matches = re.findall(r’hello’, text) print(“Case-sensitive:”, matches) # Output: [‘hello’] # Only finds lowercase…

  • List of Basic Regular Expression Patterns in Python

    Complete List of Basic Regular Expression Patterns in Python Character Classes Pattern Description Example [abc] Matches any one of the characters a, b, or c [aeiou] matches any vowel [^abc] Matches any character except a, b, or c [^0-9] matches non-digits [a-z] Matches any character in range a to z [a-z] matches lowercase letters [A-Z] Matches any character in range…

  • Programs

    Weekly Wages Removing Duplicates even ,odd Palindrome  Rotate list Shuffle a List Python random Module Explained with Examples The random module in Python provides functions for generating pseudo-random numbers and performing random operations. Here’s a detailed explanation with three examples for each important method: Basic Random Number Generation 1. random.random() Returns a random float between 0.0 and 1.0 python import…

  • Alternation and Grouping

    Complete List of Alternation and Grouping in Python Regular Expressions Grouping Constructs Capturing Groups Pattern Description Example (…) Capturing group (abc) (?P<name>…) Named capturing group (?P<word>\w+) \1, \2, etc. Backreferences to groups (a)\1 matches “aa” (?P=name) Named backreference (?P<word>\w+) (?P=word) Non-Capturing Groups Pattern Description Example (?:…) Non-capturing group (?:abc)+ (?i:…) Case-insensitive group (?i:hello) (?s:…) DOTALL group (. matches…

Leave a Reply

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