[Tutor] string to binary and back... Python 3

Alan Gauld alan.gauld at btinternet.com
Fri Jul 20 09:16:21 CEST 2012


On 20/07/12 06:48, wolfrage8765 at gmail.com wrote:

> Thanks I will give this a try. Can you explian a little further for me
> what exactly this:
>
> newhexdata = bytes("%x" % numdata, "ascii")
> line is doing? I don't quite understand the use of the "%x" % on numdata.

It is standard string formatting in pre Python 3 style.
Thus "%x" says I want a string containing a hex  number
and % numdata says use the value of hexdata to populate
the string.

Using the format method it would look like:

newhexdata = bytes("{0:x}".format(numdata), "ascii")

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





More information about the Tutor mailing list