在Python中的二进制数中添加下划线作为分隔符
我试图将十进制数转换为 17 位二进制数并在其中添加下划线作为分隔符。我正在使用以下代码 -
id = 18
get_bin = lambda x, n: format(x, 'b').zfill(n)
bin_num = get_bin(id, 17)
我得到的输出是 -
00000000000010010
我正在尝试获得以下输出 -
0_0000_0000_0001_0010
我怎么才能得到它?
回答
使用 good'ol pal,Python 的格式规范迷你语言
id = 18
width = 17
bin_num = format(id, '0{}_b'.format(width+3))
print(bin_num)
#0_0000_0000_0001_0010
- there seems to be some bug here. width 18 makes the same output. +1 anyway ..