Python 十六进制

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14678132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:08:00  来源:igfitidea点击:

Python Hexadecimal

pythonhex

提问by VikkyB

How to convert decimal to hex in the following format (at least two digits, zero-padded, without an 0x prefix)?

如何以以下格式将十进制转换为十六进制(至少两位数字,零填充,没有 0x 前缀)?

Input: 255Output:ff

输入:255输出:ff

Input: 2Output: 02

输入:2输出:02

I tried hex(int)[2:]but it seems that it displays the first example but not the second one.

我试过了,hex(int)[2:]但它似乎显示了第一个示例而不是第二个示例。

采纳答案by Martijn Pieters

Use the format()functionwith a '02x'format.

使用具有格式的format()函数'02x'

>>> format(255, '02x')
'ff'
>>> format(2, '02x')
'02'

The 02part tells format()to use at least 2 digits and to use zeros to pad it to length, xmeans lower-case hexadecimal.

02部分告诉format()使用至少 2 位数字并使用零将其填充到长度,x表示小写十六进制。

The Format Specification Mini Languagealso gives you Xfor uppercase hex output, and you can prefix the field width with #to include a 0xor 0Xprefix (depending on wether you used xor Xas the formatter). Just take into account that you need to adjust the field width to allow for those extra 2 characters:

格式规范的迷你语言也给你X大写十六进制输出,并且可以前缀字段宽度与#以包括0x0X前缀(取决于你阉羊使用xX作为格式化器)。只需考虑到您需要调整字段宽度以允许额外的 2 个字符:

>>> format(255, '02X')
'FF'
>>> format(255, '#04x')
'0xff'
>>> format(255, '#04X')
'0XFF'

回答by Yoav Kleinberger

I think this is what you want:

我认为这就是你想要的:

>>> def twoDigitHex( number ):
...     return '%02x' % number
... 
>>> twoDigitHex( 2 )
'02'
>>> twoDigitHex( 255 )
'ff'

回答by TeNeX

Another solution is:

另一种解决方案是:

>>> "".join(list(hex(255))[2:])
'ff'

Probably an archaic answer, but functional.

可能是一个古老的答案,但功能强大。