Using %x to format number to hex and number of digits
Matty Sarro
msarro at gmail.com
Fri Nov 5 15:26:42 EDT 2010
I actually was able to get it working a few minutes after posting the
question. My apologies for not posting a followup :)
I ended up using the following format:
num = 10
num = "%#0.2x"%(num)
print(num)
It works, however I'm not sure if it'd be considered very "pythonic" or not.
Thanks for your thoughts!
On Fri, Nov 5, 2010 at 2:57 PM, Chris Rebert <clp2 at rebertia.com> wrote:
> On Fri, Nov 5, 2010 at 11:23 AM, Matty Sarro <msarro at gmail.com> wrote:
> > I'm currently trying to convert a digit from decimal to hex, however I
> need
> > the full 4 digit hex form. Python appears to be shortening the form.
> > Example:
> >
> > num = 10
> > num = "%x"%(num)
> > print(num)
> >
> >>a
> >
> > num = 10
> > num = "%#x"%(num)
> > print(num)
> >
> >>0xa
> >
> > I need it to output as 0x0a, and the exercise is requiring me to use %x
> to
> > format the string. Any help would be appreciated.
>
> Use str.zfill() and add the 0x manually:
>
> num = 10
> hexdig = "%x" % num
> padded = hexdig.zfill(2) # pad with 0 if necessary
> oxd = "0x" + padded
> print(oxd)
>
> Cheers,
> Chris
> --
> http://blog.rebertia.com
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20101105/81982150/attachment-0001.html>
More information about the Python-list
mailing list