如何删除十六进制中的“0x”并获得 2 位数字

How to remove '0x' in hex and get 2 digits

我有一个十六进制输出 "Res",看起来像这样:

Res = 0x0 0x1a 0x9 0x14 0x13 0x0 

我要 - 删除每个开头的'0x' -有2位数字 - 并删除

之间的空格

即我想要这样的 Res:001a09141300

我试过 .join 但后来我想先输入 2 位数字。

这是一种解决方法:

res='0x0 0x1a 0x9 0x14 0x13 0x0'
newStr=''
for x in res.split(' '):
    x=x[2:]
    if len(x)<2:
        x='0'+x
    newStr=newStr+x

print(newStr)

输出:

001a09141300

这个怎么样:

res = '0x0 0x1a 0x9 0x14 0x13 0x0'
li = [int(s, 16) for s in res.split()]   # [0, 26, 9, 20, 19, 0]
ls = [f"{i:0>2x}" for i in li]   # ['00', '1a', '09', '14', '13', '00']
result = "".join(ls)

print(result)   # 001a09141300

您需要 Python 3.6 或更高版本才能使用 f-string。

如果您的 Python 版本低于该版本,您可以使用 ls = ["{:0>2x}".format(i) for i in li] 代替。

f"{i:0>2x}"的解释:

>2: 右对齐,宽度为 2

0左边:用0

填空space

x右边:表示为十六进制形式

res='0x0 0x1a 0x9 0x14 0x13 0x0'
hex_ls=[x.replace('0x','0') if len(x)<4 else x.replace('0x','') for x in res.split(" ")]
print("".join(hex_ls))

输出为001a09141300