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

  • re Programs

    The regular expression r’;\s*(.*?);’ is used to find and extract text that is located between two semicolons. In summary, this expression finds a semicolon, then non-greedily captures all characters up to the next semicolon. This is an effective way to extract the middle value from a semicolon-separated string. Title 1 to 25 chars The regular…

  • Examples of Python Exceptions

    Comprehensive Examples of Python Exceptions Here are examples of common Python exceptions with simple programs: 1. SyntaxError 2. IndentationError 3. NameError 4. TypeError 5. ValueError 6. IndexError 7. KeyError 8. ZeroDivisionError 9. FileNotFoundError 10. PermissionError 11. ImportError 12. AttributeError 13. RuntimeError 14. RecursionError 15. KeyboardInterrupt 16. MemoryError 17. OverflowError 18. StopIteration 19. AssertionError 20. UnboundLocalError…

  • 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…

  • Object: Methods and properties

    🚗 Car Properties ⚙️ Car Methods 🚗 Car Properties Properties are the nouns that describe a car. They are the characteristics or attributes that define a specific car’s state. Think of them as the data associated with a car object. Examples: ⚙️ Car Methods Methods are the verbs that describe what a car can do….

  • Why Python is So Popular: Key Reasons Behind Its Global Fame

    Python’s fame and widespread adoption across various sectors can be attributed to its unique combination of simplicity, versatility, and a robust ecosystem. Here are the key reasons why Python is so popular and widely used in different industries: 1. Easy to Learn and Use 2. Versatility Python supports multiple programming paradigms, including: This versatility allows…

  • Case Conversion Methods in Python

    Case Conversion Methods in Python (Syntax + Examples) Python provides several built-in string methods to convert text between different cases (uppercase, lowercase, title case, etc.). Below are the key methods with syntax and examples: 1. upper() – Convert to Uppercase Purpose: Converts all characters in a string to uppercase.Syntax: python string.upper() Examples: python text = “Hello, World!”…

Leave a Reply

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