python b'...' notation

jmfauth wxjmfauth at gmail.com
Fri May 31 03:51:55 EDT 2013


On 31 mai, 00:19, alcyon <st... at terrafirma.us> wrote:
> On Wednesday, May 29, 2013 3:19:42 PM UTC-7, Cameron Simpson wrote:
> > On 29May2013 13:14, Ian Kelly <ian.g.ke... at gmail.com> wrote:
>
> > | On Wed, May 29, 2013 at 12:33 PM, alcyon <st... at terrafirma.us> wrote:
>
> > | > This notation displays hex values except when they are 'printable', in which case it displays that printable character.  How do I get it to force hex for all bytes?  Thanks, Steve
>
> > |
>
> > | Is this what you want?
>
> > |
>
> > | >>> ''.join('%02x' % x for x in b'hello world')
>
> > | '68656c6c6f20776f726c64'
>
> > Not to forget binascii.hexlify.
>
> > --
>
> > Cameron Simpson <c... at zip.com.au>
>
> > Every particle continues in its state of rest or uniform motion in a straight
>
> > line except insofar as it doesn't.      - Sir Arther Eddington
>
> Thanks for the binascii.hexlify tip. I was able to make it work but I did have to write a function to get it exactly the string I wanted.  I wanted, for example, <b'\n\x00'> to display as <0x0A 0x00> or <b'!\xff(\xc0'> to display as <0x21 0xFF 0x28 0xC0>.

--------

>>> a = b'!\xff(\xc0\n\x00'
>>> z = ['0x{:02X}'.format(c) for c in b]
>>> z
['0x21', '0xFF', '0x28', '0xC0', '0x0A', '0x00']
>>> s = ' '.join(z)
>>> s
'0x21 0xFF 0x28 0xC0 0x0A 0x00'
>>>

jmf




More information about the Python-list mailing list