从匹配的模式中获取所有出现并拆分
get all occurrences from a matched pattern and split
我正在使用以下代码查找从索引 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]
我手动使用每个索引以显示以下输出,我想创建一个可以拆分的函数并且 return 每次出现
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
built-in 功能:
outputs = s.split('~')
这里是 outputs
值:
['product 1 & product 2|category 1|8',
'product 4|category 3 |10',
'product 1 & product 19|category 8|6',
'product 50|category 4|6']
我正在使用以下代码查找从索引 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]
我手动使用每个索引以显示以下输出,我想创建一个可以拆分的函数并且 return 每次出现
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
built-in 功能:
outputs = s.split('~')
这里是 outputs
值:
['product 1 & product 2|category 1|8',
'product 4|category 3 |10',
'product 1 & product 19|category 8|6',
'product 50|category 4|6']