Re: Using %x to format number to hex and number of digits

Discussion in 'Python' started by Chris Rebert, Nov 5, 2010.

  1. Chris Rebert

    Chris Rebert Guest

    On Fri, Nov 5, 2010 at 11:23 AM, Matty Sarro <> 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
     
    Chris Rebert, Nov 5, 2010
    #1
    1. Advertising

  2. On Fri, Nov 5, 2010 at 11:23 AM, Matty Sarro <> 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.


    http://docs.python.org/release/2.5.2/lib/typesseq-strings.html

    What you're asking for is called "zero padding", so if I were you, I'd
    search the above page for the phrase "zero pad".

    --
    Grant Edwards grant.b.edwards Yow! BARBARA STANWYCK makes
    at me nervous!!
    gmail.com
     
    Grant Edwards, Nov 5, 2010
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. aefxx
    Replies:
    1
    Views:
    595
    Virgil Green
    Dec 17, 2004
  2. Replies:
    10
    Views:
    6,223
    Neredbojias
    Aug 19, 2005
  3. Bengt Richter
    Replies:
    6
    Views:
    474
    Juha Autero
    Aug 19, 2003
  4. Tim Chase
    Replies:
    2
    Views:
    556
    Tim Chase
    Nov 6, 2010
  5. chirs
    Replies:
    3
    Views:
    168
    Dr John Stockton
    Dec 1, 2003
Loading...

Share This Page