Python 从匹配的图案中获取所有引用并拆分
我使用下面的代码查找从索引0到~的所有索引,这样我就可以为每个匹配创建一行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
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结合使用