英文:
Python print formatted hex number in string
问题
print("Setting new address: [%s %s]->[%s %s]" % (hex(a[0]), hex(a[1]), hex(a[2]), hex(a[3])))
英文:
How to format number as hex inside string in print with efficient way? Basically I wanted to print a hex number in any position of string.
a = [1, 2, 10, 30]
# this is working, but not very optimal, once it could have multiple entries
print("Setting new address: [%s %s]->[%s %s]", hex(a[0]), hex(a[1]), hex(a[2]), hex(a[3]))
# I was trying something like this, but didn't work like I wanted
print("Setting new address: %s" % [f'0x{x:02x}' for x in a])
My expecting result is
Setting new address: [0x01 0x02]->[0x0a 0x14]
Thanks
答案1
得分: 0
"OK, I will answer by myself..."
a = [1, 2, 10, 30]
print("Setting new address [%s %s]->[%s %s]" % tuple(["0x" + hex(x)[2:].zfill(2) for x in a]))
and the result is:
Setting new address [0x01 0x02]->[0x0a 0x1e]
英文:
OK, I will answer by myself...
a = [1, 2, 10, 30]
print("Setting new address [%s %s]->[%s %s]" % tuple(["0x" + hex(x)[2:].zfill(2) for x in a]))
and the result is:
Setting new address [0x01 0x02]->[0x0a 0x1e]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论