Python中的多重分割

2 投票
4 回答
2727 浏览
提问于 2025-04-16 02:30

我想知道怎么把一个字符串按照两个相对的符号来分割?比如说 () 是“分隔符”,我有一个这样的字符串:

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

我需要得到这样的输出(以数组的形式)

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

4 个回答

0

使用正则表达式来匹配两个()字符:

import re
re.split('[()]', string)
1

在这个特定的情况下,听起来先按空格分开,然后再去掉括号会更合理。

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

嗯……再读一遍问题,你想保留一些空格,所以可能不太适合这样做 :) 不过我还是把这个想法保留在这里。

13

re.split()

s = "Wouldn't it be (most) beneficial to have (at least) some idea?"
l = re.split('[()]', s);

撰写回答