Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从匹配的图案中获取所有引用并拆分_Python_String_For Loop_Delimiter_Substr - Fatal编程技术网

Python 从匹配的图案中获取所有引用并拆分

Python 从匹配的图案中获取所有引用并拆分,python,string,for-loop,delimiter,substr,Python,String,For Loop,Delimiter,Substr,我使用下面的代码查找从索引0到~的所有索引,这样我就可以为每个匹配创建一行 import re s = 'product 1 & product 2|category 1|8~product 4|category 3 |10~product 1 & product 19|category 8|6~product 50|category 4|6' substring = "~" matches = re.finditer(substring, s) mat

我使用下面的代码查找从索引0到~的所有索引,这样我就可以为每个匹配创建一行

import re
s = 'product 1 & product 2|category 1|8~product 4|category 3 |10~product 1 & product 19|category 8|6~product 50|category 4|6'

substring = "~"

matches = re.finditer(substring, s)

matches_positions = [match.start() for match in matches]

print(matches_positions)

output 
[34, 59, 95]
为了显示以下输出,我手动使用每个索引,我想创建一个可以拆分并返回每个事件的函数

print(s[0:34])
print(s[34 + 1: 59])
print(s[59 +1 : 95])
print(s[95 +1 : len(s)])


output

product 1 & product 2|category 1|8
product 4|category 3 |10
product 1 & product 19|category 8|6
product 50|category 4|6

事先谢谢

您只需使用
str.split
内置功能即可:

outputs = s.split('~')
以下是
输出值
值:

['product 1 & product 2|category 1|8',
 'product 4|category 3 |10',
 'product 1 & product 19|category 8|6',
 'product 50|category 4|6']

你需要使用正则表达式吗?为什么不使用拆分?i、 e.
s.split(“~”)
。如果我使用正则表达式,这没关系,让我尝试将它与explode结合使用,我只是尝试在函数中这样做,以便将我的输出与Pandas结合使用