[Python-ideas] Readability of hex strings (Was: Use of coding cookie in 3.x stdlib)

Nick Coghlan ncoghlan at gmail.com
Wed Jul 28 06:39:41 CEST 2010

(another attempt at getting this discussion over on python-ideas where
it belongs)

On Tue, Jul 27, 2010 at 10:12 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> Since it only takes a pair of small helper functions to convert hex
> dumps in the form "XXXX XXXX ..." to and from byte strings, I don't see
> the need for new syntax and would vote -1 on the idea. However, I'd
> vote +0 on a matching bytes.tohex() method to partner with the existing
> bytes.fromhex().

Having written my own bytes formatting function to do exactly as
Anatoly asks (i.e. display a string of binary data as hex characters
with spaces between each byte), I can understand the desire to have
something like that readily available.

The following is not particularly intuitive:
>>> " ".join(format(c, "x") for c in b"abcdefABCDEF")
'61 62 63 64 65 66 41 42 43 44 45 46'

The 2.x equivalent is just as bad:
>>> " ".join(format(ord(c), "x") for c in "abcdefABCDEF")
'61 62 63 64 65 66 41 42 43 44 45 46'

However, I'll caveat that support by pointing out that the basic
formatting quickly becomes inadequate for many purposes. Personally, I
quickly replaced it with a fixed width dump format that provides the
ASCII character dumps over on the right hand side the way most hex
editors do).


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list