Python字符串操作-拆分、切片、从HEX转换为DEC



我有以下字符串:

s = "0015CB,0,0,01,006D,0016CF1,4,000D,01,0202,01,0E09,01,02,00,006D,0000,0,0,01,006D,00F4E7D,1,000D,01,0202,01,0E09,01,02,00,006D,0000,0,0,01,006D,0008184,8,000D,01,0202,01,0E09,01,02,00,006D,0000,0,0,01,006D,00FA704,9,000D,01,0202,01,0E09,01,02,00,006D,0000,0,0,01,006D,0014EC8,2,000D,01,0202,01,0E09,01,02,00,006D,0000,0,0,01,006D,00FAEEA,9,000D,01,0202,01,0E09,01,02,00,006D,0000,0,0,01,006D,00FADE9,5,000D,01,0202,01,0E09,01,02,00,006D,0000,0,0,01,006D,00FA5A5,3,000D"

Selcuk在000D的每一次迭代中都帮助分解,因此提取的第一个值是0016CF1,4

现在,我需要帮助将该值的第一部分从Hex转换为Dec,并在逗号后保留数字。因此,它将是93425,493425 4

到目前为止,我有以下几种,它很有效,但不是很优雅,请一些人帮忙让它更高效/更干净。谢谢

my_list = [e[-9:] for e in s.split(",000D")]
print(my_list)
# Output = ['0016CF1,4', '00F4E7D,1', '0008184,8', '00FA704,9', '0014EC8,2', '00FAEEA,9', '00FADE9,5', '00FA5A5,3', '']

# for testing print the first value from the list [0]
# output = 0016CF1,4
print(my_list[0])
# save my_list in a string called list and remove the comma and check digit
# output = 0016CF1
list=str(my_list)
result = [e[-7:] for e in list.split(",")]
print(result[0])
# convert the first value from HEX to DEC
# output= 93425
res1 = int(result[0],16)
print(res1)
#  get the checkdigit for the first value in the list
checkdigit = [f[-1:] for f in s.split(",000D")]
print(checkdigit[0])
# output = 4
#  join res1 and checkdigit
print(res1,checkdigit[0])
# output = 93425 4

理想情况下,我希望以上内容循环使用,这样原始列表中的所有值都会像示例第一个值abvove一样进行转换。感谢

这里有一个非常紧凑的解决方案:

my_list = ['0016CF1,4', '00F4E7D,1', '0008184,8', '00FA704,9',
'0014EC8,2', '00FAEEA,9', '00FADE9,5', '00FA5A5,3']
result = [f'{int(x[:-2], 16)} {x[-1]}' for x in my_list]

以下是result:的最终内容

['93425 4', '1003133 1', '33156 8', '1025796 9',
'85704 2', '1027818 9', '1027561 5', '1025445 3']

相关内容

  • 没有找到相关文章

最新更新