0% completed
Escape characters in Python are used to include special characters in strings that would otherwise be difficult or impossible to represent. They are prefixed with a backslash (\
) and allow us to format text, insert special characters, or control string behavior.
Escape characters are useful when working with strings that contain quotes, newlines, tabs, or special symbols, making them essential for proper string formatting and manipulation.
Here is a table of common escape characters in Python, each with a description and example:
Escape Character | Description | Example Usage | Output |
---|---|---|---|
\\ | Backslash | "This is a backslash \\\\" | This is a backslash \ |
\' | Single quote | 'It\'s a single quote' | It's a single quote |
\" | Double quote | "He said, \"Hello\"" | He said, "Hello" |
\n | Newline | "First line\nSecond line" | Prints on two lines |
\t | Horizontal tab | "Column 1\tColumn 2" | Column 1 Column 2 |
\r | Carriage return (Moves cursor to start of line) | "Hello\rWorld" | World replaces Hello |
\b | Backspace (Deletes previous character) | "ABC\b" | AB |
\f | Form feed (New page effect in some systems) | "Page\fNew page" | Page + form feed effect |
\ooo | Character with octal value ooo | "\101" (A) | A |
\xhh | Character with hex value hh | "\x41" (A) | A |
\"
escape sequence allows double quotes inside a string.\n
creates a newline, so the second sentence starts on a new line.She said, "Python is amazing!"
Let's learn escape characters.
Escape characters in Python allow you to format strings efficiently and include special characters such as newlines, tabs, and quotes. They help in handling string formatting, improving readability, and ensuring compatibility with different text processing scenarios.
.....
.....
.....