Escape Sequence Characters

Learn how to use escape sequence characters in Python to handle special characters like quotes, newlines, tabs, and more. This guide covers common escape sequences with examples to help you write cleaner, error-free Python strings.

Loading...
Escape Sequence Characters

To insert characters that cannot be used directly in a string, you can use an escape character. An example of such a character is a double quote inside a string that is surrounded by double quotes.

print("This will give "error")

Escape sequence characters are represented with a backslash (\) followed by a specific character or combination of characters.

print("This will run without any \" error")
#output: This will run without any " error

Common Escape Sequences in Python

  1. \\ - Backslash: The backslash itself is an escape character, so to print a literal backslash, you need to escape it with another backslash.

    print("This is a backslash: \\")
    #output: This is a backslash: \
  2. \' - Single Quote: This allows you to insert a single quote inside a string that is enclosed by single quotes.

    print('This is a \'single quote\'')
    #output: This is a 'single quote'
  3. \" - Double Quote: Similar to the single quote escape sequence, this allows you to insert double quotes inside a string that is surrounded by double quotes.

    print("This is a \"double quote\"")
    #output: This is a "double quote"
  4. \n - Newline: Inserts a newline, causing the text after it to appear on a new line.

    print("Line 1\nLine 2")
    #output: 
    #Line 1
    #Line 2
  5. \t - Tab: Inserts a tab space, which is often used for indentation.

    print("First\tSecond")
    #output: First   Second
  6. \\b - Backspace: Removes the character immediately before it.

    print("Hello\bWorld")
    #output: HellWorld
  7. \r - Carriage Return: Moves the cursor back to the beginning of the line.

    print("Hello\rWorld")
    # output: World
     
    # The \r escape sequence moves the cursor to the beginning of the line, so the text "World" overwrites the text "Hello."

Support my work!