LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   In Python, printing leading zero for hex numbers 0 through f (https://www.linuxquestions.org/questions/programming-9/in-python-printing-leading-zero-for-hex-numbers-0-through-f-719426/)

donpar 04-15-2009 06:17 PM

In Python, printing leading zero for hex numbers 0 through f
 
Hello,

This is probably a simple question for an experienced Python person:

This is a little python program that gets 3 random hex numbers and prints them out:


import random

hn1 = (hex(random.randint(0,63))[2:])
hn2 = (hex(random.randint(0,255))[2:])
hn3 = (hex(random.randint(0,255))[2:])

print (hn1,":",hn2,":",hn3,sep="")


Example Result: 37:bc:31

All is fine & dandy except when the hex number is from 0 through f. In that case the result may be 7b:5:5c
I'd actually like it to be 7b:05:5c

Is there a simple way of formatting this?

Many thanks,

Don P

rriggs 04-15-2009 07:09 PM

Don't convert the numbers to hex strings with hex(). Use print formatting to format the numbers.

>>> print '%02X:%02X:%02X' % (12, 21, 129)
0C:15:81

Or

>>> hx='%02X:%02X:%02X' % (12, 21,129)
>>> print hx
0C:15:81

Regards


All times are GMT -5. The time now is 03:38 PM.