装饰 Hex 函数以填充零

2023-11-30

我写了这个简单的函数:

def padded_hex(i, l):
    given_int = i
    given_len = l

    hex_result = hex(given_int)[2:] # remove '0x' from beginning of str
    num_hex_chars = len(hex_result)
    extra_zeros = '0' * (given_len - num_hex_chars) # may not get used..

    return ('0x' + hex_result if num_hex_chars == given_len else
            '?' * given_len if num_hex_chars > given_len else
            '0x' + extra_zeros + hex_result if num_hex_chars < given_len else
            None)

例子:

padded_hex(42,4) # result '0x002a'
hex(15) # result '0xf'
padded_hex(15,1) # result '0xf'

虽然这对我来说足够清楚并且适合我的用例(用于简单打印机的简单测试工具),但我不禁认为还有很大的改进空间,并且可以将其压缩为非常简洁的东西。

解决这个问题还有哪些其他方法?


从 Python 3.6 开始,您可以:

>>> value = 42
>>> padding = 6
>>> f"{value:#0{padding}x}"
'0x002a'

对于较旧的 python 版本,请使用.format()字符串方法:

>>> "{0:#0{1}x}".format(42,6)
'0x002a'

解释:

{   # Format identifier
0:  # first parameter
#   # use "0x" prefix
0   # fill with zeroes
{1} # to a length of n characters (including 0x), defined by the second parameter
x   # hexadecimal number, using lowercase letters for a-f
}   # End of format identifier

如果您希望字母十六进制数字大写,但前缀带有小写“x”,则需要一些解决方法:

>>> '0x{0:0{1}X}'.format(42,4)
'0x002A'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

装饰 Hex 函数以填充零 的相关文章

随机推荐