简体   繁体   English

Python中的整数到十六进制转换

[英]Integer to Hexadecimal Conversion in Python

a = 1
print hex(a)

The above gives me the output: 0x1以上给了我输出: 0x1

How do I get the output as 0x01 instead?如何将输出改为0x01

You can use format :您可以使用format

>>> a = 1
>>> '{0:02x}'.format(a)
'01'
>>> '0x{0:02x}'.format(a)
'0x01'
>>> format(1, '#04x') 
'0x01'
print "0x%02x"%a

x as a format means "print as hex" . x作为格式的意思是“打印为十六进制”
02 means "pad with zeroes to two characters" . 02表示“用零填充两个字符”

Try:尝试:

print "0x%02x" % a

It's a little hairy, so let me break it down:它有点毛茸茸,所以让我分解一下:

The first two characters, "0x" are literally printed.前两个字符“0x”按字面打印。 Python just spits them out verbatim. Python 只是逐字逐句地吐出它们。

The % tells python that a formatting sequence follows. % 告诉 python 遵循格式化序列。 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. 0 告诉格式化程序它应该用零填充任何前导空格,而 2 告诉它至少使用两列来做到这一点。 The x is the end of the formatting sequence and indicates the type - hexidecimal. x 是格式化序列的结尾,表示类型 - 十六进制。

If you wanted to print "0x00001", you'd use "0x%05x", etc.如果你想打印“0x00001”,你可以使用“0x%05x”等。

You can use format :您可以使用格式

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

Here is f-string variant for Python 3.6+:这是 Python 3.6+ 的 f-string 变体:

a = 1
print(f"{a:0>2x}")

Explanation of string formatting:字符串格式说明:

  • : : format specifier : :格式说明
  • 0 : fill (with 0 ) 0 :填充(用0
  • > : right-align field > : 右对齐字段
  • 2 : width 2 : 宽度
  • x : hex type x : hex类型

Source: 6.1.3.1 Format Specification Mini-Language来源: 6.1.3.1 格式规范迷你语言

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM