fork download
  1. import re
  2. from pprint import pprint
  3.  
  4. def explode(s, keywords):
  5. for k in keywords:
  6. m = re.search(r'(%s~[^~]*)(?:~|$)' % (re.escape(k),), s)
  7. yield m and m.group(1)
  8.  
  9.  
  10. lst = [
  11. ['171000', 'Thing..Mega~Corporate~Thing..Mid~Dairy~Thing..Micro~Cheese', 'Cheese', '0.012174'],
  12. ['171000', 'Thing..Mega~Corporate', 'Cheese', '0.012174'],
  13. ]
  14.  
  15. print("Before:")
  16. pprint(lst)
  17.  
  18. for row in lst:
  19. row[1:2] = explode(row[1], "Mega Mid Micro".split())
  20.  
  21. print("\nAfter:")
  22. pprint(lst)
Success #stdin #stdout 0.03s 6700KB
stdin
Standard input is empty
stdout
Before:
[['171000',
  'Thing..Mega~Corporate~Thing..Mid~Dairy~Thing..Micro~Cheese',
  'Cheese',
  '0.012174'],
 ['171000', 'Thing..Mega~Corporate', 'Cheese', '0.012174']]

After:
[['171000',
  'Mega~Corporate',
  'Mid~Dairy',
  'Micro~Cheese',
  'Cheese',
  '0.012174'],
 ['171000', 'Mega~Corporate', None, None, 'Cheese', '0.012174']]