装饰十六进制功能以填充零 [英] Decorating Hex function to pad zeros
问题描述
我写了这个简单的函数:
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'
虽然这对我来说很清楚,并且适合我的用例(用于简单打印机的简单测试工具),但我不禁认为还有很多改进的余地,并且可以将其缩小为非常简洁的内容. /p>
还有什么其他方法可以解决这个问题?
使用新的 说明: 如果您希望字母十六进制数字为大写字母,但前缀为小写字母"x",则需要采取一些变通方法: 从Python 3.6开始,您还可以执行以下操作: I wrote this simple function: Examples: Whilst this is clear enough for me and fits my use case (a simple test tool for a simple printer) I can't help thinking there's a lot of room for improvement and this could be squashed down to something very concise. What other approaches are there to this problem? Use the new Explanation: If you want the letter hex digits uppercase but the prefix with a lowercase 'x', you'll need a slight workaround: Starting with Python 3.6, you can also do this:
这篇关于装饰十六进制功能以填充零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!{ # 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
>>> '0x{0:0{1}X}'.format(42,4)
'0x002A'
>>> value = 42
>>> padding = 6
>>> f"{value:#0{padding}x}"
'0x002a'
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'
.format()
string method:>>> "{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
>>> '0x{0:0{1}X}'.format(42,4)
'0x002A'
>>> value = 42
>>> padding = 6
>>> f"{value:#0{padding}x}"
'0x002a'