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

  • Predefined Character Classes

    Predefined Character Classes Pattern Description Equivalent . Matches any character except newline \d Matches any digit [0-9] \D Matches any non-digit [^0-9] \w Matches any word character [a-zA-Z0-9_] \W Matches any non-word character [^a-zA-Z0-9_] \s Matches any whitespace character [ \t\n\r\f\v] \S Matches any non-whitespace character [^ \t\n\r\f\v] 1. Literal Character a Matches: The exact character…

  • Type Conversion Functions

    Type Conversion Functions in Python πŸ”„ Type conversion (or type casting) transforms data from one type to another. Python provides built-in functions for these conversions. Here’s a comprehensive guide with examples: 1. int(x) πŸ”’ Converts x to an integer. Python 2. float(x) afloat Converts x to a floating-point number. Python 3. str(x) πŸ’¬ Converts x…

  • Method overriding

    Method overriding is a key feature of object-oriented programming (OOP) and inheritance. It allows a subclass (child class) to provide its own specific implementation of a method that is already defined in its superclass (parent class). When a method is called on an object of the child class, the child’s version of the method is…

  • Polymorphism

    Polymorphism is a core concept in OOP that means “many forms” 🐍. In Python, it allows objects of different classes to be treated as objects of a common superclass. This means you can use a single function or method to work with different data types, as long as they implement a specific action. πŸŒ€ Polymorphism…

  • re.sub()

    Python re.sub() Method Explained The re.sub() method is used for searching and replacing text patterns in strings. It’s one of the most powerful regex methods for text processing. Syntax python re.sub(pattern, repl, string, count=0, flags=0) Example 1: Basic Text Replacement python import re text = “The color of the sky is blue. My favorite color is blue too.” #…

  • Static Methods

    The primary use of a static method in Python classes is to define a function that logically belongs to the class but doesn’t need access to the instance’s data (like self) or the class’s state (like cls). They are essentially regular functions that are grouped within a class namespace. Key Characteristics and Use Cases General…

Leave a Reply

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