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

Posted

技术标签:

【中文标题】Python子字符串 - 将第n个字符拆分到某个字符串的左侧【英文标题】:Python Substring - Splitting nth number of Characters to the left of a certain string 【发布时间】:2020-11-10 07:09:37 【问题描述】:

我有以下示例字符串:

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 功能,并且正在努力掌握正则表达式。

【问题讨论】:

【参考方案1】:

不需要正则表达式,您可以使用拆分和切片的组合:

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

【讨论】:

非常感谢,我花了几个小时试图找到解决方案,非常感谢。【参考方案2】:

与此非常接近的东西应该适合您...

string = "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"
sub = []
search = "000D"
while string.find(search) != -1:
   pos = string.find(search)
   sub.append(string[pos-10:pos])
   string = string[pos+len(search):]
print(sub)

输出:

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

只是搜索和子串,然后切断字符串。

编辑:我修复了 cmets 中指出的错误

【讨论】:

这是一个无限循环。即使它有效,它也将是非常低效的。见Shlemiel the painter’s algorithm。

以上是关于Python子字符串 - 将第n个字符拆分到某个字符串的左侧的主要内容,如果未能解决你的问题,请参考以下文章

将二进制字符串拆分为长度为 n 的子字符串,然后解码 R 中的每个子字符串

将java中的字符串拆分为固定长度的块

拆分一个字符串并将其放入两个数组中

python 每n个字符拆分一次

java定义固定长度字符串_将java中的字符串拆分为固定长度的块

如何在iOS上将字符串拆分为子字符串?