开发者

Multi-split in Python

开发者 https://www.devze.com 2023-01-11 04:04 出处:网络
How would I split a string by two opposing values? For example ( and ) are the \"deliminators\" and I have the following string:

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?']
0

精彩评论

暂无评论...
验证码 换一张
取 消