The question came up in the forum how to represent an integer as a hexadecimal. There were two obvious ways to do this, the hex() function and the format operator %X. The resulting strings 0xac23b and AC23B look different. If you have to display the result, AC23B might be your choice. Otherwise speed might be important, particularly, if you call the function a lot. Here is a way to measure speed ...
# two different ways to represent integer 705083 as a hexadecimal number
# 0x is the official prefix for a hexnumber
# the results appear different, but both are of type string and change back to base 10 properly
# using the hex() function
hex1 = hex(705083)
print hex1, type(hex1), int(hex1,16) # result = 0xac23b <type 'str'> 705083
# using the format operator %
hex2 = "%X" % 705083
print hex2, type(hex2), int(hex2, 16) # result = AC23B <type 'str'> 705083
# let's time the two options ...
import timeit
t = timeit.Timer('hex(705083)')
elapsed = (10 * t.timeit(number=100000))
print 'Function hex(705083) takes %0.3f micro-seconds/pass' % elapsed
t = timeit.Timer('"%X" % 705083')
elapsed = (10 * t.timeit(number=100000))
print 'The format operator takes %0.3f micro-seconds/pass' % elapsed
Last edited by vegaseat : Mar 1st, 2007 at 3:47 pm. Reason: [code=python] tag
May 'the Google' be with you!