Escape Characters

Python Escape Characters

Python escape characters are special sequences that allow us to represent characters that are difficult or impossible to type directly in strings.

Escape Character List:

\\n: Newline - Moves the cursor to the next line.

        
# Example: Newline
print("Hello\nWorld")  # Output: Hello (newline) World
        
    

\\t: Tab - Adds a tab space.

        
# Example: Tab
print("Tab\tSpace")     # Output: Tab    Space
        
    

\\\\: Backslash - Represents a backslash character.

        
# Example: Backslash
print("Backslash\\")    # Output: Backslash\
        
    

\\': Single Quote - Escapes a single quote inside single-quoted strings.

        
# Example: Single Quote
print("It\'s a test")   # Output: It's a test
        
    

\\": Double Quote - Escapes a double quote inside double-quoted strings.

        
# Example: Double Quote
print('She said, \"Hello!\"')  # Output: She said, "Hello!"
        
    

\\r: Carriage Return - Moves the cursor to the beginning of the current line.

        
# Example: Carriage Return
print("Hello\rWorld")  # Output: World (since 'Hello' is overwritten)
        
    

\\b: Backspace - Moves the cursor one position back.

        
# Example: Backspace
print("Helloo\b")  # Output: Helloo (removes one 'o')
        
    

\\f: Form Feed - Moves the cursor to the next page.

        
# Example: Form Feed (depends on terminal/console support)
print("Hello\fWorld")  # Output: Hello (form feed) World
        
    

\\v: Vertical Tab - Moves the cursor down a tab (less commonly used).

        
# Example: Vertical Tab
print("Hello\vWorld")  # Output: Hello (vertical tab) World
        
    

\\xhh: Character with a hexadecimal value.

        
# Example: Hexadecimal Value
print("\x41")  # Output: 'A' (ASCII of 41 in hexadecimal)
        
    

\\ooo: Character with an octal value.

        
# Example: Octal Value
print("\141")  # Output: 'a' (ASCII of 141 in octal)