Thomson
Thomson

Reputation: 21664

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.

Upvotes: 3

Views: 1159

Answers (1)

Kevin J. Chase
Kevin J. Chase

Reputation: 3956

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 10FFFF16". 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.

Upvotes: 2

Related Questions