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

  • Quantifiers (Repetition)

    Quantifiers (Repetition) in Python Regular Expressions – Detailed Explanation Basic Quantifiers 1. * – 0 or more occurrences (Greedy) Description: Matches the preceding element zero or more times Example 1: Match zero or more digits python import re text = “123 4567 89″ result = re.findall(r’\d*’, text) print(result) # [‘123’, ”, ‘4567’, ”, ’89’, ”] # Matches…

  • Random Module?

    What is the Random Module? The random module in Python is used to generate pseudo-random numbers. It’s perfect for: Random Module Methods with Examples 1. random() – Random float between 0.0 and 1.0 Generates a random floating-point number between 0.0 (inclusive) and 1.0 (exclusive). python import random # Example 1: Basic random float print(random.random()) # Output: 0.5488135079477204 # Example…

  • circle,Rational Number

    1. What is a Rational Number? A rational number is any number that can be expressed as a fraction where both the numerator and the denominator are integers (whole numbers), and the denominator is not zero. The key idea is ratio. The word “rational” comes from the word “ratio.” General Form:a / b Examples: Non-Examples: 2. Formulas for Addition and Subtraction…

  • Raw Strings in Python

    Raw Strings in Python’s re Module Raw strings (prefixed with r) are highly recommended when working with regular expressions because they treat backslashes (\) as literal characters, preventing Python from interpreting them as escape sequences. path = ‘C:\Users\Documents’ pattern = r’C:\Users\Documents’ .4.1.1. Escape sequences Unless an ‘r’ or ‘R’ prefix is present, escape sequences in string and bytes literals are interpreted according…

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

  • String Validation Methods

    Complete List of Python String Validation Methods Python provides several built-in string methods to check if a string meets certain criteria. These methods return True or False and are useful for input validation, data cleaning, and text processing. 1. Case Checking Methods Method Description Example isupper() Checks if all characters are uppercase “HELLO”.isupper() → True islower() Checks if all…

Leave a Reply

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