Python escape characters


Answers ( 1 )

  1. In Python, escape characters are used to insert characters in a string that are otherwise difficult to type or to represent special characters. They are preceded by a backslash (). Here are some commonly used escape characters in Python:

    1. \n: Inserts a newline in the text at this point.
    2. \t: Inserts a tab in the text at this point.
    3. \: Inserts a backslash character in the text.
    4. ': Inserts a single quote character in the text.
    5. ": Inserts a double quote character in the text.
    6. \r: Carriage return - returns the cursor to the start of the line without advancing to the next line.
    7. \b: Inserts a backspace in the text.
    8. \f: Inserts a formfeed in the text.
    9. \ooo: Inserts a character with the specified octal value (ooo).
    10. \xhh: Inserts a character with the specified hexadecimal value (hh).

    Here's an example in Python that demonstrates some of these escape characters:

    # Example of escape characters in Python
    print("Line1\nLine2")  # Newline example
    print("Column1\tColumn2")  # Tab example
    print("This is a backslash: \\")  # Backslash example
    print("He said, \"Hello!\"")  # Double quote example

    In this code:

    • \n creates a new line.
    • \t creates a horizontal tab space.
    • \\ is used to display the backslash character itself.
    • \" is used to include a double quote inside a string enclosed by double quotes.

Leave an answer