Split the string L at the character DELIM.
But don't split within groups nested in ([{}]) or in strings.
>>> split_list1 ('12345', ',')
['12345']
>>> split_list1 ('123, [45, 67], (89,[10,11],12), 13', ',')
['123', '[45, 67]', '(89,[10,11],12)', '13']
>>> split_list1 ('12, "34,56", 78', ',')
['12', '"34,56"', '78']
>>> dq='"'
>>> sq="'"
>>> bs='\\\\'
>>> len(bs)
1
>>> split_list1 ('12, "34,56", '+sq+'11,12'+sq+', 78', ',')
['12', '"34,56"', "'11,12'", '78']
>>> split_list1 ('12, "34,56'+bs+dq+',99", '+sq+'11,12'+sq+', 78', ',')
['12', '"34,56\\\\",99"', "'11,12'", '78']
>>> split_list1 ('12, "34,56'+bs+bs+dq+',99, '+sq+'11,12'+sq+', 78', ',')
['12', '"34,56\\\\\\\\"', '99', "'11,12'", '78']
Definition at line 3 of file split_list.py.
3def split_list1 (l, delim):
4 """Split the string L at the character DELIM.
5But don't split within groups nested in ([{}]) or in strings.
6
7>>> split_list1 ('12345', ',')
8['12345']
9>>> split_list1 ('123, [45, 67], (89,[10,11],12), 13', ',')
10['123', '[45, 67]', '(89,[10,11],12)', '13']
11>>> split_list1 ('12, "34,56", 78', ',')
12['12', '"34,56"', '78']
13>>> dq='"'
14>>> sq="'"
15>>> bs='\\\\'
16>>> len(bs)
171
18>>> split_list1 ('12, "34,56", '+sq+'11,12'+sq+', 78', ',')
19['12', '"34,56"', "'11,12'", '78']
20>>> split_list1 ('12, "34,56'+bs+dq+',99", '+sq+'11,12'+sq+', 78', ',')
21['12', '"34,56\\\\",99"', "'11,12'", '78']
22>>> split_list1 ('12, "34,56'+bs+bs+dq+',99, '+sq+'11,12'+sq+', 78', ',')
23['12', '"34,56\\\\\\\\"', '99', "'11,12'", '78']
24"""
25 i = 0
26 out = []
27 sz = len(l)
28 while i < sz:
29 nest = 0
30 j = i
31 while j < sz:
32 c = l[j]
33 if c == delim and nest == 0:
34 break
35 elif c in '[{(':
36 nest += 1
37 elif c in '])}':
38 if nest == 0: break
39 nest -= 1
40 elif c in '\'"':
41 j += 1
42 esc = False
43 while j < sz and not (l[j] == c and not esc):
44 if esc:
45 esc = False
46 elif l[j] == '\\':
47 esc = True
48 j += 1
49 j += 1
50 out.append (l[i:j])
51 i = j+1
52 while i < sz and l[i] == ' ':
53 i += 1
54 return out
55
56