
Question:
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?"]
Solution:1
re.split()
s = "Wouldn't it be (most) beneficial to have (at least) some idea?" l = re.split('[()]', s);
Solution:2
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.
Solution:3
Use a regular expression, matching both ()
characters:
import re re.split('[()]', string)
Solution:4
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?']
Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
EmoticonEmoticon