修饰十六进制函数以填充零

2024-05-19 22:25:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一个简单的函数:

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'

虽然这对我来说已经足够清楚,并且符合我的用例(一个简单打印机的简单测试工具),但我还是忍不住认为还有很大的改进空间,可以将它压缩成非常简洁的东西。

这个问题还有什么其他的解决方法?


Tags: 函数lenifdefzerosresultextraelse
3条回答

使用*传递宽度,使用X传递大写

print '0x%0*X' % (4,42) # '0x002A'

georgAshwini Chaudhary建议

使用新的^{}字符串方法:

>>> "{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'

从Python3.6开始,您还可以执行以下操作:

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

这个怎么样:

print '0x%04x' % 42

相关问题 更多 >