[Tutor] str format conversion help

Alan Gauld alan.gauld at btinternet.com
Wed Jul 14 21:27:00 CEST 2010


"eMyListsDDg" <emylistsddg at gmail.com> wrote 

First please start new threads wirth a new email, do not reply to 
a previous post - it confuses threaded readers. (and sometimes 
human readers too!)

> '\x00\x11\xb2\x00@,O\xa4'
> 
> the above str is being returned from one key/value pair in 
> a dictionary. it is the addr of a network device.
> 
> i want to store the addr's in their 8byte mac format like this,
> 
>    [00 11 b2 00 40 2C 4F A4]

Thats what you've got. The string is merely a representation 
of that data.

> the combinations of format strings using the print statement 
> hasn't resulted in what i need.

format strings are used to display data not to store it.
Do you really want to display the data in the format you've 
shown? Or do you really want to store it as 8 bytes?

The two concepts are completely different and more 
or less unrelated.

> looking for a suggestion on how to format this, 
> '\x00\x11\xb2\x00@,O\xa4' into this [00-11-B2-00-40-2C-4F-A4]

OK, to display it you need to extract each byte and convert it to 
a string representing the hex value. Fortunately you an treat a 
string of bytes as charactrers and the hex() function will give you 
the hex representation. So...

print "[%s]" % ('-'.join([hex(v) for v in theValue]) )

should be close...

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list