darkthief
darkthief

Reputation: 13

How do I split a string into a list without removing the delimiter

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

Answers (5)

mozway
mozway

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

pppig
pppig

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

Adon Bilivit
Adon Bilivit

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

Christian Sloper
Christian Sloper

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

Francisco
Francisco

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

Related Questions