jon*_*jon 54 python hex padding built-in
我写了这个简单的函数:
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)
虽然这对我来说足够清楚并且适合我的用例(一个简单的打印机简单的测试工具),我不禁想到有很大的改进空间,这可以被压缩到非常简洁的东西.
还有哪些方法可以解决这个问题?
Tim*_*ker 141
使用新的.format()字符串方法:
>>> "{0:#0{1}x}".format(42,6)
'0x002a'
Run Code Online (Sandbox Code Playgroud)
说明:
{ # 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
Run Code Online (Sandbox Code Playgroud)
如果你想要字母十六进制数字大写但前缀小写'x',你需要一个小的解决方法:
>>> '0x{0:0{1}X}'.format(42,4)
'0x002A'
Run Code Online (Sandbox Code Playgroud)
从Python 3.6开始,您也可以这样做:
>>> value = 42
>>> padding = 6
>>> f"{value:#0{padding}x}"
'0x002a'
Run Code Online (Sandbox Code Playgroud)
geo*_*org 24
这个怎么样:
print '0x%04x' % 42
Run Code Online (Sandbox Code Playgroud)
小智 13
如果只是为了前导零,你可以试试zfill函数。
'0x' + hex(42)[2:].zfill(4) #'0x002a'
Run Code Online (Sandbox Code Playgroud)
我需要的是
"{:02x}".format(7) # '07'
"{:02x}".format(27) # '1b'
Run Code Online (Sandbox Code Playgroud)
其中:是的开始格式化规范为第一个参数{}到.format(),则02是指“垫从左侧与输入0s到长度2”和x装置“的格式与小写字母的十六进制”。
以上也可以用 f-strings 来完成:
f"{7:02x}" # '07'
f"{27:02x}" # '1b'
Run Code Online (Sandbox Code Playgroud)
使用*通过宽度和X大写
print '0x%0*X' % (4,42) # '0x002A'
Run Code Online (Sandbox Code Playgroud)
正如georg和Ashwini Chaudhary所建议的那样
如果您想保留前面的十六进制表示法,0x您也可以尝试使用 python3 f-strings的方法。
f'0x{10:02x}' # 0x0a
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
63531 次 |
| 最近记录: |