views:

111

answers:

4

How would I split a string by two opposing values? For example ( and ) are the "deliminators" and I have the following string:

Wouldn't it be (most) beneficial to have (at least) some idea?

I need the following output (as an array)

["Wouldn't it be ", "most", " beneficial to have ", "at least", " some idea?"]
+12  A: 

re.split()

s = "Wouldn't it be (most) beneficial to have (at least) some idea?"
l = re.split('[()]', s);
quantumSoup
+1 for not re-inventing the wheel.
muhuk
nice and simple :)
townsean
A: 

You can use the split of a regular expression:

import re
pattern = re.compile(r'[()]')
pattern.split("Wouldn't it be (most) beneficial to have (at least) some idea?")
["Wouldn't it be ", 'most', ' beneficial to have ', 'at least', ' some idea?']
DiggyF
You don't need to escape the `()` inside a character class.
KennyTM
A: 

Use a regular expression, matching both () characters:

import re
re.split('[()]', string)
jtbandes
+1  A: 

In this particular case, sounds like it would make more sense to first split by space and then trim the brackets.

out = []
for element in "Wouldn't it be (most) beneficial to have (at least) some idea?".split():
  out.append(element.strip('()'))

Hm... re-reading the question, you wanted to preserve some of the spaces, so maybe not :) but keeping it here still.

Jaanus
@Jaanus: I would *prefer* to keep spaces.
Josh K