Liondancer
Liondancer

Reputation: 16469

Splitting string by '],[', but keeping the brackets

Ive got a string in this format

a = "[a,b,c],[e,d,f],[g,h,i]"

Each part I want to be split is separated by ],[. I tried a.split("],[") and I get the end brackets removed.

In my example that would be:

["[a,b,c","e,d,f","g,h,i]"]

I was wondering if there was a way to keep the brackets after the split?

Desired outcome:

["[a,b,c]","[e,d,f]","[g,h,i]"]

Upvotes: 1

Views: 2169

Answers (3)

Jivan
Jivan

Reputation: 23078

The other answers are correct, but here is another way to go.

Important note: this is just to present another option that may prove useful in certain cases. Don't do it in the general case, and do so only in you're absolutely certain that you have the control over the expression you're passing into exec statement.

# provided you declared a, b, c, d, e, f, g, h, i beforehand
>>> exp = "[a,b,c],[e,d,f],[g,h,i]"
>>> exec("my_object = " + exp)
>>> my_object
([a,b,c],[e,d,f],[g,h,i])

Then, you can do whatever you like with my_object.

Provided that you have full control over exp, this way of doing sounds more appropriate and Pythonic to me because you are treating a piece of Python code written in a string as a... piece of Python code written in a string (hence the exec statement). Without manipulating it through regexp or artificial hacks.

Just keep in mind that it can be dangerous.

Upvotes: 1

dragon2fly
dragon2fly

Reputation: 2419

Python is very flexible, so you just have to manage it a bit and be adaptive to your case.

In [8]:a = "[a,b,c],[e,d,f],[g,h,i]"
       a.replace('],[','] [').split(" ")
Out[8]:['[a,b,c]', '[e,d,f]', '[g,h,i]']

Upvotes: 2

user2555451
user2555451

Reputation:

The problem is that str.split removes whatever substring you split on from the resulting list. I think it would be better in this case to use the slightly more powerful split function from the re module:

>>> from re import split
>>> a = "[a,b,c],[e,d,f],[g,h,i]"
>>> split(r'(?<=\]),(?=\[)', a)
['[a,b,c]', '[e,d,f]', '[g,h,i]']
>>>

(?<=\]) is a lookbehind assertion which looks for ]. Similarly, (?=\[) is a lookahead assertion which looks for [. Both constructs are explained in Regular Expression Syntax.

Upvotes: 6

Related Questions