Python 打印格式化的十六进制字符串

huangapple go评论52阅读模式
英文:

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]

huangapple
  • 本文由 发表于 2023年5月6日 19:16:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76188569.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定