我写了这个简单的函数:
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)
Run Code Online (Sandbox Code Playgroud)
例子:
padded_hex(42,4) # result '0x002a'
hex(15) # result '0xf'
padded_hex(15,1) # result '0xf'
Run Code Online (Sandbox Code Playgroud)
虽然这对我来说足够清楚并且适合我的用例(一个简单的打印机简单的测试工具),我不禁想到有很大的改进空间,这可以被压缩到非常简洁的东西.
还有哪些方法可以解决这个问题?
是否可以使用 Ansible / Jinja2 中的格式化字符串将列表/字典列表转换为字符串列表?
我知道我可以做类似的事情:
{{["First: %d", "Second: %d"] | map("format", 1) | join(", ") }}
Run Code Online (Sandbox Code Playgroud)
要得到First: 1, Second 1。
是否可以做类似的事情
{{[[1, 1], [2, 2]] | map("format", "Num %d, %d") | join(", ") }}
Run Code Online (Sandbox Code Playgroud)
并导致Num 1, 1, Num 2, 2?