[Python-ideas] Stop displaying elements of bytes objects as printable ASCII characters in CPython 3

Chris Lasher chris.lasher at gmail.com
Thu Sep 11 19:51:38 CEST 2014


On Thu, Sep 11, 2014 at 9:42 AM, Ron Adam <ron3200 at gmail.com> wrote:

>
>
> On 09/10/2014 09:40 PM, Nick Coghlan wrote:
>
>> On 11 September 2014 11:36, Ron Adam<ron3200 at gmail.com>  wrote:
>>
>>> >When working with hex data, I prefer the way hex editors do it.  With
>>> pairs
>>> >of hex digits separated by a space.
>>> >
>>> >      "50 79 74 68 6f 6e"    b'Python'
>>> >
>>> >But I'm not sure there's a way to make that work cleanly. :-/
>>>
>> I realised (http://bugs.python.org/issue22385) we could potentially
>> support that style through the string formatting syntax, using the
>> precision field to specify the number of "bytes per chunk", along with
>> a couple of the other existing formatting flags in the mini-language:
>>
>> format(b"xyz", "x") -> '78797a'
>> format(b"xyz", "X") -> '78797A'
>> format(b"xyz", "#x") -> '0x78797a'
>>
>> format(b"xyz", ".1x") -> '78 79 7a'
>> format(b"abcdwxyz", ".4x") -> '61626364 7778797a'
>> format(b"abcdwxyz", "#.4x") -> '0x61626364 0x7778797a'
>>
>> format(b"xyz", ",.1x") -> '78,79,7a'
>> format(b"abcdwxyz", ",.4x") -> '61626364,7778797a'
>> format(b"abcdwxyz", "#,.4x") -> '0x61626364,0x7778797a'
>>
>
> Is there a way to go in the other direction?  That is these other hex
> formats to bytes?
>
>
Yes, for the forms not prefixed with '0x':

>>> bytes.fromhex('78797A')
b'xyz'
>>> bytes.fromhex('78797a')
b'xyz'
>>> bytes.fromhex('78 79 7a')
b'xyz'
>>> bytes.fromhex('0x78797a')
Traceback (most recent call last):
  File "<ipython-input-11-1cc0b196bfc3>", line 1, in <module>
    bytes.fromhex('0x78797a')
ValueError: non-hexadecimal number found in fromhex() arg at position 0
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20140911/77fd505b/attachment-0001.html>


More information about the Python-ideas mailing list