Concise way to format list/array to custom(hex) string
Grant Edwards
grante at visi.com
Sat Aug 2 09:29:20 EDT 2008
On 2008-08-02, Zoltán Nagy <abesto0 at gmail.com> wrote:
> Kurien Mathew írta:
>> Hello,
>>
>> What will be a concise & efficient way to convert a list/array.array of
>> n elements into a hex string? For e.g. given the bytes
>> [116, 111, 110, 103, 107, 97]
>> I would like the formatted string
>> 0x74 0x6f 0x6e 0x67 0x6b 0x61
>>
>> Is there an approach better than below:
>> hex = ''
>> for b in bytes:
>> hex += ('0x%x '%b)
>>
><snip>
>
> You should avoid multiple string additions, as each one creates a new
> string object (str objects are immutable). Try this:
>
> bytes = [116, 111, 110, 103, 107, 97]
> string = ''.join( ['0x%x '%b for b in bytes] )
That results in an extra ' ' and the end of the string. Try
this:
string = ' '.join(['0x%02x' % b for b in bytes])
--
Grant Edwards grante Yow! ... Just enough
at time to do my LIBERACE
visi.com impression...
More information about the Python-list
mailing list