Reputation: 13
I have a string '[0, 0, 0], [0, 0, 0], [0, 0, 0]'
I want to split it into a list like ['[0, 0, 0]', '[0, 0, 0]', '[0, 0, 0]']
Upvotes: 1
Views: 104
Reputation: 260975
Using a regex and re.split
:
import re
s = '[0, 0, 0], [0, 0, 0], [0, 0, 0]'
out = re.split('(?<=]),\s*', s)
output: ['[0, 0, 0]', '[0, 0, 0]', '[0, 0, 0]']
Upvotes: 0
Reputation: 1275
It also handles [
or ]
appearing in character elements.
import re
print(re.split(r"(?<=]), *?(?=\[)", '[0, 0, 0, "[", "]"], [0, 0, 0], [0, 0, 0]'))
# ['[0, 0, 0, "[", "]"]', '[0, 0, 0]', '[0, 0, 0]']
Upvotes: 0
Reputation: 27043
You can achieve that with this:
import ast
L = '[0, 0, 0], [0, 0, 0], [0, 0, 0]'
O = [str(p) for p in ast.literal_eval(L)]
print(O)
Output:
['[0, 0, 0]', '[0, 0, 0]', '[0, 0, 0]']
Upvotes: 0
Reputation: 7510
You could use regular expression like this:
import re
re.findall('\[.*?\]', '[0, 0, 0], [0, 0, 0], [0, 0, 0]')
which produces the result:
['[0, 0, 0]', '[0, 0, 0]', '[0, 0, 0]']
Note to use of '*?' in the pattern to make it non-greedy (otherwise it would just match everything between first [ and last ].
Upvotes: 0
Reputation: 11486
You could use ast.literal_eval
:
>>> ast.literal_eval('[0, 0, 0], [0, 0, 0], [0, 0, 0]')
([0, 0, 0], [0, 0, 0], [0, 0, 0])
This also parses the inner lists, which you might not want to.
It's not that complicated to convert the inner lists back to strings if you desire:
>>> [str(inner) for inner in ast.literal_eval('[0, 0, 0], [0, 0, 0], [0, 0, 0]')]
['[0, 0, 0]', '[0, 0, 0]', '[0, 0, 0]']
Upvotes: 1