2
votes

I have the following

str = '[5.955894, 45.817792], [10.49238, 45.817792], [10.49238, 47.808381], [5.955894, 47.808381]'

I want to split it so that I have an array of strings like

['[5.955894, 45.817792]', '[10.49238, 45.817792]', ...]

So that the [...] objects are elements of the array. It is important that the enclosing [ and ] are included. I've come so far:

re.split('\D,\s\D', str)

But that gives me:

['[5.955894, 45.817792', '10.49238, 45.817792', '10.49238, 47.808381', '5.955894, 47.808381]']

Not really what I want.

4
eval('[' + str + ']') if it comes from trusted source. - nhahtdh
What do you want to achieve ultimately? - nhahtdh
Second line of code in my question. That's what I want. - grssnbchr
@nhahtdh -- that eval won't give what OP wants, but as a side note, there is ast.literal_eval which would do the same thing as eval without the security implications. - mgilson

4 Answers

9
votes

I prefer to use re.findall and specify what I want instead of trying to describe the delimiter for re.split

>>> s = '[5.955894, 45.817792], [10.49238, 45.817792], [10.49238, 47.808381], [5.955894, 47.808381]'
>>> re.findall(r"\[[^\]]*\]",s)
['[5.955894, 45.817792]', '[10.49238, 45.817792]', '[10.49238, 47.808381]', '[5.955894, 47.808381]']
  1. \[ matches [
  2. [^\]]* matches anything but ]
  3. \] matches ]
3
votes

You need to use re.split with look-ahead:

>>> s = '[5.955894, 45.817792], [10.49238, 45.817792], [10.49238, 47.808381], [5.955894, 47.808381]'

>>> re.split(",[ ]*(?=\[)", s)
['[5.955894, 45.817792]', '[10.49238, 45.817792]', '[10.49238, 47.808381]', '[5.955894, 47.808381]']

And don't use str as variable. It's shadows the built-in.

The below pattern:

,[ ]*(?=\[)

will match the comma(,) and some whitespaces, which is followed by a [

You can even do it with look-behind. So, (?<=\]),[ ]* will also work.

0
votes

Here is a naive procedure I've written, I think it solves your problem but couldn't be the best.

>>>def split_string(strg, begin = '[', end = ']'):  
    myList = []  
    string = ''  
    for char in strg:  
        if char == begin:  
            string = ''  
        string += char  
        if char == end:  
            myList.append(string)  
    return myList  
>>>strg = '[5.955894, 45.817792], [10.49238, 45.817792], [10.49238, 47.808381], [5.955894, 47.808381]'  
>>>split_string(strg)  
['[5.955894, 45.817792]', '[10.49238, 45.817792]', '[10.49238, 47.808381]', '[5.955894, 47.808381]']
0
votes

Following on from @nhahtdh comment.

Depends on your trust issues.

In [510]: txt = '[5.955894, 45.817792], [10.49238, 45.817792], [10.49238, 47.808381], [5.955894, 47.808381]'

In [511]: lst = eval ("[%s]" % txt)

In [512]: [str(x) for x in lst]
Out[512]:
['[5.955894, 45.817792]',
 '[10.49238, 45.817792]',
 '[10.49238, 47.808381]',
 '[5.955894, 47.808381]']