简体   繁体   中英

Escape sequences in strings using ASCII values in decimal?

Escape sequences in Python support both hex (like '\\xab' ) and octal (like \\12 ) values. Is there a way to specify the ASCII code as a decimal value (probably like \\n99 )? I searched a little bit but was surprised to find nothing.

What you're looking for doesn't exist in Python.

Numeric escape codes are typically in hex (or less frequently, octal), because that's the obvious choice for their intended uses. From the table in The Python Language Reference , 2.4.1. String and Bytes literals :

Notes:
[...]
3. In a bytes literal, hexadecimal and octal escapes denote the byte with the given value. In a string literal, these escapes denote a Unicode character with the given value.

(Emphasis added. Thanks to Evert for providing the link in a comment .)

To represent a byte , you must specify exactly 8 bits. At 4 bits per hex digit, this requires exactly two hex digits. Converting 8 bits to 2 hex digits and back is much easier than converting those same 8 bits to and from two-point-something decimal digits --- there's no need to multiply (or divide) by 16 in your head.

To represent a Unicode character , you must specify a code point in the Unicode code space , which is defined as "a range of integers from 0 to 10FFFF 16 ". Since these are officially represented in hexadecimal ( U+0020 , U+FFFE , etc.), hex escape codes are the only reasonable choice --- they require literally no effort at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM