Escape sequences – special characters

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.

CharacterMeaning
\Backslash and newline ignored
\nLinefeed
\fFormfeed
\tHorizontal Tab
\vVertical Tab
\rCarriage Return
\bBackspace
\\Backslash
\’Single Quote
\”Double Quote

Example

print("first \t \
line \nsecond \t line \n\"Lorem Ipsum\"")
Output
first    line 
second   line 
"Lorem Ipsum"
Code Explanation

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).

  1. The print function is called with a single argument, a string.
  2. The string is defined using string concatenation.
  3. The first line of the string is "first \t ", which includes the text “first” followed by a tab character (\t).
  4. The next line of the string is "line \n", which includes the text “line” followed by a newline character (\n).
  5. The third line of the string is "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).
  6. The fourth and final line of the string is "\"Lorem Ipsum\"", which includes the text “Lorem Ipsum” surrounded by double quotes (").
  7. The string concatenation combines these individual strings into a single string, with newline characters separating the lines and tab characters used to create indents.
  8. The final string is passed as an argument to the print function, which outputs the string to the console.