代码之家  ›  专栏  ›  技术社区  ›  Josh K

python中的多重分割

  •  2
  • Josh K  · 技术社区  · 14 年前

    如何将字符串拆分为两个相反的值?例如 ( ) 是“除沫器”,我有以下字符串:

    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 回复  |  直到 14 年前
        1
  •  13
  •   quantumSoup    14 年前

    re.split ()

    s = "Wouldn't it be (most) beneficial to have (at least) some idea?"
    l = re.split('[()]', s);
    
        2
  •  1
  •   Jaanus    14 年前

    在这种特殊情况下,听起来先按空格分割,然后修剪括号更有意义。

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

    Hm.…重新阅读这个问题,你想要保留一些空间,所以也许不是:)但是保持它在这里。

        3
  •  0
  •   jtbandes    14 年前

    使用正则表达式,两者都匹配 () 字符:

    import re
    re.split('[()]', string)
    
        4
  •  0
  •   SiggyF    14 年前

    可以使用正则表达式的拆分:

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