In Python, escape sequences are special characters that are used to represent characters that are difficult or impossible to type directly in a string literal. Escape sequences are composed of a backslash (\) followed by one or more characters that have a special meaning.
Here are some of the most commonly used escape sequences in Python:
\\: backslash\': single quote\": double quote\n: newline\t: tab\b: backspace\r: carriage return\f: form feedHere's an example of using escape sequences in a string:
print('Hello, \'world\'!\n\tHow are you?') |
This code will output:
Hello, 'world'! How are you? |
In this example, the escape sequences \’ and \n are used to represent a single quote and a newline character, respectively. The escape sequence \t is used to insert a tab character, which creates an indentation.
Escape sequences are also commonly used to represent special characters in regular expressions and other contexts where character encoding is important.