Python十六进制 [英] Python Hexadecimal
问题描述
如何将十进制转换为以下格式的十六进制(至少两位数,零填充,不带0x前缀)?
输入: 255
输出: ff
输入: 2 输出:
02
[2:] 但它似乎显示了第一个例子,但不是第二个例子。 使用 格式rel =noreferrer> format()
函数,其格式为'02x'
。 / p>
>>>格式(255,'02x')
'ff'
>>>格式(2,'02x')
'02'
02 部分告诉 format()
使用至少2位数字并使用零填充长度, x
表示小写十六进制。
格式规范迷你语言 还可以为大写十六进制输出提供 X
,并且您可以在#
的前面添加一个 0x
或 0X
前缀(取决于您使用的格式) x
或 X
>。请注意,您需要调整字段宽度以允许额外的2个字符:
>>>格式(255,'02X')
'FF'
>>>格式(255,'#04x')
'0xff'
>>>格式(255,'#04X')
'0XFF'
How to convert decimal to hex in the following format (at least two digits, zero-padded, without an 0x prefix)?
Input: 255
Output:ff
Input: 2
Output: 02
I tried hex(int)[2:]
but it seems that it displays the first example but not the second one.
Use the format()
function with a '02x'
format.
>>> format(255, '02x')
'ff'
>>> format(2, '02x')
'02'
The 02
part tells format()
to use at least 2 digits and to use zeros to pad it to length, x
means lower-case hexadecimal.
The Format Specification Mini Language also gives you X
for uppercase hex output, and you can prefix the field width with #
to include a 0x
or 0X
prefix (depending on wether you used x
or X
as the formatter). Just take into account that you need to adjust the field width to allow for those extra 2 characters:
>>> format(255, '02X')
'FF'
>>> format(255, '#04x')
'0xff'
>>> format(255, '#04X')
'0XFF'
这篇关于Python十六进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!