Home > Net >  Split string with comma(,) and exclude list in python
Split string with comma(,) and exclude list in python

Time:01-19

I have a string

'[abc, def, ijk],somedata1,somedata2,somedata3,somedata4'

I want to split it as below:

[['abc', 'def', 'ijk'], 'somedata1', 'somedata2', 'somedata3', 'somedata4']

But when I use .split(',') the list also splits

'[abc, def, ijk],somedata1,somedata2,somedata3,somedata4'.split(',')

Output:

['[abc', ' def', ' ijk]', 'somedata1', 'somedata2', 'somedata3', 'somedata4']

Is there a way in Python to split with , but exclude lists?

CodePudding user response:

A simple trick would be to put quotes around the existing strings to be able to use ast.literal_eval:

import ast
import re

s = '[abc, def, ijk],somedata1,somedata2,somedata3,somedata4'
data = list(ast.literal_eval(re.subn(r'(\w )', r"'\1'", s)[0]))

It gives as expected:

[['abc', 'def', 'ijk'], 'somedata1', 'somedata2', 'somedata3', 'somedata4']

But beware: any more complex string containing quotes would immediately break this code...

  •  Tags:  
  • Related