为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

月关宝盒 2023-03-22 16:19:01
我有以下字符串: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现在我需要帮助将这个值的第一部分从十六进制转换为十进制,并将逗号后面的数字保留原样。所以它会是93425,4或93425 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,4print(my_list[0])# save my_list in a string called list and remove the comma and check digit# output = 0016CF1list=str(my_list)result = [e[-7:] for e in list.split(",")]print(result[0])# convert the first value from HEX to DEC# output= 93425res1 = int(result[0],16)print(res1)#  get the checkdigit for the first value in the listcheckdigit = [f[-1:] for f in s.split(",000D")]print(checkdigit[0])# output = 4#  join res1 and checkdigitprint(res1,checkdigit[0])# output = 93425 4理想情况下,我希望在循环中使用上面的内容,以便原始列表中的所有值都像示例中的第一个值一样进行转换。谢谢
查看完整描述

1 回答

?
梦里花落0921

TA贡献1772条经验 获得超6个赞

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


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']


查看完整回答
反对 回复 2023-03-22
  • 1 回答
  • 0 关注
  • 161 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信