gpt4 book ai didi

Python 子字符串 - 将第 n 个字符拆分到某个字符串的左侧

转载 作者:行者123 更新时间:2023-12-04 01:18:02 24 4
gpt4 key购买 nike

我有以下示例字符串:

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

请问我如何在 "000D" 的每次迭代中获取左侧的 9 个字符,因此第一个结果将是:

0016CF1,4

第二次提取将是:

00F4E7D,1

第三个是:

0008184,8

等我已经尝试过 split 函数,但很难掌握正则表达式。

最佳答案

不需要正则表达式,你可以使用 split 和 slice 的组合:

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"

my_list = [e[-9:] for e in s.split(",000D")]
print(my_list)

输出:

['0016CF1,4', '00F4E7D,1', '0008184,8', '00FA704,9', '0014EC8,2', '00FAEEA,9', '00FADE9,5', '00FA5A5,3', '']

关于Python 子字符串 - 将第 n 个字符拆分到某个字符串的左侧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63005445/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com