Integer to Hexadecimal Conversion in Python

雨燕双飞 提交于 2020-01-02 04:41:09

问题


a = 1
print hex(a)

The above gives me the output: 0x1

How do I get the output as 0x01 instead?


回答1:


You can use format :

>>> a = 1
>>> '{0:02x}'.format(a)
'01'
>>> '0x{0:02x}'.format(a)
'0x01'



回答2:


>>> format(1, '#04x') 
'0x01'



回答3:


Try:

print "0x%02x" % a

It's a little hairy, so let me break it down:

The first two characters, "0x" are literally printed. Python just spits them out verbatim.

The % tells python that a formatting sequence follows. The 0 tells the formatter that it should fill in any leading space with zeroes and the 2 tells it to use at least two columns to do it. The x is the end of the formatting sequence and indicates the type - hexidecimal.

If you wanted to print "0x00001", you'd use "0x%05x", etc.




回答4:


print "0x%02x"%a

x as a format means "print as hex".
02 means "pad with zeroes to two characters".




回答5:


You can use format:

>>> "0x"+format(1, "02x")
'0x01'


来源:https://stackoverflow.com/questions/28650857/integer-to-hexadecimal-conversion-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!