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)
["Woul开发者_如何学Pythondn't it be ", "most", " beneficial to have ", "at least", " some idea?"]
re.split()
s = "Wouldn't it be (most) beneficial to have (at least) some idea?"
l = re.split('[()]', s);
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.
Use a regular expression, matching both ()
characters:
import re
re.split('[()]', string)
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?']
精彩评论