【问题标题】:Python String Manipulation - Split, Slice, Convert from HEX to DECPython 字符串操作 - 拆分、切片、从 HEX 转换为 DEC
【发布时间】:2020-11-10 17:49:10
【问题描述】:

我有以下字符串:

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,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

理想情况下,我希望在循环中使用上述内容,以便原始列表中的所有值都像上面的示例第一个值一样转换。谢谢

【问题讨论】:

    标签: python string split hex slice


    【解决方案1】:

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

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

    【讨论】:

    • 非常感谢您抽出宝贵的时间来回答这个问题,但是您能否告诉我如何使用我的原始列表“my_list”来进行字符串操作,或者我需要做些什么吗?其他使这项工作?当我使用我的 'my_list' 或 'list' - 我得到错误:results = [f'{int(x[:-2], 16)} {x[-1]}' for x in list] ValueError:基数为 16 的 int() 的无效文字:''
    • @MB4ig 那是因为我的列表中有一个空元素,去掉它!
    • 啊!非常感谢 Riccardo,非常感谢 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-01
    • 2020-02-10
    • 2019-07-31
    • 2020-09-12
    • 2014-09-23
    相关资源
    最近更新 更多