Escape sequences in Python are special characters that are used to represent specific non-printable characters in strings. These characters are represented by a backslash followed by a specific character. For example, the escape sequence “\n” represents a newline character, while “\t” represents a tab character.
Escape sequences are useful when you want to insert special characters into your strings, such as when you’re printing output to the console or writing to a file. They allow you to represent characters that might not otherwise be able to be typed or printed.
It’s important to keep in mind that escape sequences are interpreted by Python and are not part of the actual string value. This means that when you print or write a string that contains an escape sequence, the actual character represented by the escape sequence will be displayed or written, rather than the escape sequence itself.
Character | Meaning |
---|---|
\ | Backslash and newline ignored |
\n | Linefeed |
\f | Formfeed |
\t | Horizontal Tab |
\v | Vertical Tab |
\r | Carriage Return |
\b | Backspace |
\\ | Backslash |
\’ | Single Quote |
\” | Double Quote |
print("first \t \
line \nsecond \t line \n\"Lorem Ipsum\"")
first line
second line
"Lorem Ipsum"
This code is a Python script that creates a multi-line string. The string is created by concatenating several strings, separated by newline characters (\n
) and tab characters (\t
).
print
function is called with a single argument, a string."first \t "
, which includes the text “first” followed by a tab character (\t
)."line \n"
, which includes the text “line” followed by a newline character (\n
)."second \t line \n"
, which includes the text “second” followed by a tab character (\t
) and then the text “line”, followed by a newline character (\n
)."\"Lorem Ipsum\""
, which includes the text “Lorem Ipsum” surrounded by double quotes ("
).print
function, which outputs the string to the console.