The ASCII encoding assigns a unique number to each character, called an encoded value. In Python, an ASCII character can be represented by its encoded value, in addition to its entity (that is, the real character). This indirect use of encoded values to represent characters is called an escape character.
The ASCII encoding contains a total of 128 characters. \ 0 and \ x can only be followed by a maximum of two digits, this cause the octal form \ 0 cannot represent all ASCII characters. Only the hexadecimal form \ x can represent all ASCII characters.
We have been talking about ASCII encoding, and did not mention other encodings (character sets) such as Unicode, GBK, Big5, etc., because Python escape characters are only valid for ASCII encoding (128 characters).
Characters 1, 2, 3, x, y, and z correspond to the octal form of the ASCII code 61, 62, 63, 170, 171, 172, and the hexadecimal form are 31, 32, 33, 78, 79, 7A. The following example illustrates the use of escape characters:
str1 = "Oct: \061\062\063" str2 = "Hex: \x31\x32\x33\x78\x79\x7A" print(str1) print(str2)
The output is:
Oct: 123
Hex: 123xyz
Note that escape characters in octal form cannot show xyz because their encoded values have three digits after being converted to octal.
For ASCII encoding, characters in the range of 0 ~ 31 (decimal) are characters which under control. They are invisible and cannot be displayed on the output devices or even entered from the keyboard. They can only be expressed in the form of escape characters. However, directly using ASCII code to memorize is not convenient, and it is not easy to understand. Therefore, for common control characters, C language also defines a shorthand method. The complete list of Python escape character is as follows.
Escape Characters | Explanations |
---|---|
\n | A newline character moves the cursor position to the beginning of the next line. |
\r | A carriage return moves the cursor to the beginning of the same line. |
\t | The horizontal tab, or Tab, is generally equivalent to four spaces. |
\a | The buzzer rings. Note that instead of sounding from the horn, many computers today do not have a buzzer, so the bell may not be effective. |
\b | Backspace, move the cursor position to the previous column. |
\\ | Backslash |
\’ | Single quote |
\’’ | Double quote |
\ | Continuation character at the end of the string line, that is, one line is not completed, go to the next line to continue writing. |
Example:
#Use \t horizontal tab or tab str1 = 'Hi, \t \t Welcome \t \t \t to \t \t my \t \t webpage' str2 = 'Hi, \n Welcome \n to \n my \n webpage' print (str1) print (str2)
The output is:
Hi, Welcome to my webpage
Hi,
Welcome
to
More Tutorials:
Python Installation - Linux (Ubuntu)More Python Exercises:
Python String Exercises