【问题标题】:Python: How can I include the delimiter(s) in a string split? [duplicate]Python:如何在字符串拆分中包含分隔符? [复制]
【发布时间】:2014-02-08 02:25:45
【问题描述】:

我想用多个分隔符拆分一个字符串,但将分隔符保留在结果列表中。我认为这对于解析任何类型的公式的初始步骤很有用,我怀疑有一个不错的 Python 解决方案。

有人在 Java here 中提出了类似的问题。

例如,典型的拆分如下所示:

>>> s='(twoplusthree)plusfour'
>>> s.split(f, 'plus')
['(two', 'three)', 'four']

但我正在寻找一种将加号重新添加(或保留)的好方法:

['(two', 'plus', 'three)', 'plus', 'four']

最终我想对每个运算符和括号都这样做,所以如果有办法得到

['(', 'two', 'plus', 'three', ')', 'plus', 'four']

一口气完成,那就更好了。

【问题讨论】:

    标签: python string parsing split


    【解决方案1】:

    您可以使用 Python 的 re 模块来做到这一点。

    import re
    s='(twoplusthree)plusfour'
    list(filter(None, re.split(r"(plus|[()])", s)))
    

    如果你只需要一个迭代器,你可以省略列表。

    【讨论】:

      【解决方案2】:
      import re
      s = '(twoplusthree)plusfour'
      l = re.split(r"(plus|\(|\))", s)
      a = [x for x in l if x != '']
      print a
      

      输出:

      ['(', 'two', 'plus', 'three', ')', 'plus', 'four']
      

      【讨论】:

        【解决方案3】:

        这是使用re.split 的简单方法:

        import re
        
        s = '(twoplusthree)plusfour'
        re.split('(plus)',  s)
        

        输出:

        ['(two', 'plus', 'three)', 'plus', 'four']
        

        re.split 与string.split 非常相似,不同之处在于您传递的是正则表达式模式,而不是文字分隔符。这里的技巧是将 () 放在模式周围,以便将其作为一个组提取。

        请记住,如果分隔符模式连续出现两次,则您将获得空字符串

        【讨论】:

          【解决方案4】:

          这个帖子很旧,但由于它的谷歌搜索结果我想添加这个:

          如果您不想使用正则表达式,可以使用更简单的方法。基本上只是调用split,但是除了最后一个标记之外放回分隔符

          def split_keep_deli(string_to_split, deli):
              result_list = []
              tokens = string_to_split.split(deli)
              for i in xrange(len(tokens) - 1):
                  result_list.append(tokens[i] + deli)
              result_list.append(tokens[len(tokens)-1])
              return  result_list
          

          【讨论】:

            【解决方案5】:

            这里我在第一次出现字母字符时分割一个字符串:

            def split_on_first_alpha(i):
                #i="3.5 This is one of the way"
                split_1=re.split(r'[a-z]',i,maxsplit=1, flags=re.IGNORECASE)
                find_starting=re.findall(r'[a-z]',i,flags=re.IGNORECASE)
                split_1[1]=find_starting[0]+split_1[1]
                return split_1
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2018-10-10
              • 1970-01-01
              • 1970-01-01
              • 2012-02-14
              • 1970-01-01
              相关资源
              最近更新 更多