Latest LQ Deal: Latest LQ Deals
Go Back > Forums > Non-*NIX Forums > Programming
User Name
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.


  Search this Thread
Old 04-15-2009, 07:17 PM   #1
LQ Newbie
Registered: Feb 2006
Location: Sunnyvale, CA
Distribution: RH Enterprise 5 and 6, RHEV 2.2
Posts: 2

Rep: Reputation: 0
In Python, printing leading zero for hex numbers 0 through f


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
Old 04-15-2009, 08:09 PM   #2
Registered: Mar 2009
Location: Colorado, US
Distribution: Fedora 13, Fedora 14, RHEL6 Beta
Posts: 46

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

>>> print '%02X:%02X:%02X' % (12, 21, 129)


>>> hx='%02X:%02X:%02X' % (12, 21,129)
>>> print hx




Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Nice script to convert numbers between bases (bin/dec/oct/hex) hgate73 Linux - General 4 02-17-2009 04:51 AM
printing 64 bit hex number lilzz Linux - Newbie 8 08-20-2006 09:16 PM
How to convert a float to its binary or hex representation in Python? zero79 Programming 1 09-01-2005 11:19 AM
How to convert a float to its binary or hex representation in Python? zero79 Linux - Software 1 08-29-2005 10:30 PM
printing numbers without using semicolon vijeesh_ep Programming 18 09-08-2004 12:59 PM > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 06:04 PM.

Main Menu
Write for LQ is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration