【问题标题】:Split string up to nth occurrence of separator将字符串拆分到第 n 次出现的分隔符
【发布时间】:2020-04-21 14:07:29
【问题描述】:

我有一个字符串 -

"one:two:three:four:five:six:seven:eight".

现在我想用 ':' 分割这个字符串,但是直到前 3 次出现 ':'。

预期输出 -

['one','two','three','four:five:six:seven:eight'].

我该怎么做?

【问题讨论】:

    标签: python python-3.x split


    【解决方案1】:

    split 采用除分隔符之外的 maxsplit 参数,这正是这样做的:

    s.split(':',3)
    # ['one', 'two', 'three', 'four:five:six:seven:eight']
    

    【讨论】:

      【解决方案2】:

      您可以使用 split for all 然后根据需要构建列表的形状。

      str_list = "one:two:three:four:five:six:seven:eight"
      my_list = str_list.split(":")
      
      print([my_list[0], my_list[1], my_list[2], ":".join(my_list[3:])])
      

      输出将是:

      ['one', 'two', 'three', 'four:five:six:seven:eight']
      

      【讨论】:

        【解决方案3】:

        或者如果你想使用正则表达式包:re

        import re
        re.split(':', "one:two:three:four:five:six:seven:eight", maxsplit=3)
        # ['one', 'two', 'three', 'four:five:six:seven:eight']
        

        如果你想编译正则表达式

        import re
        re_colon = re.compile(':')
        re_colon("one:two:three:four:five:six:seven:eight", maxsplit=3)
        # ['one', 'two', 'three', 'four:five:six:seven:eight']
        

        【讨论】:

          【解决方案4】:

          python 中的 split 函数可以接受 2 个参数,即 第一个参数是您必须用来拆分字符串的字符。 第二个参数是 max_split,一个整数,表示最大编号。分裂。

          given_string = "one:two:three:four:five:six:seven:eight"
          
          print(given_string.split(':',3))
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2011-07-31
            • 2013-03-11
            • 2019-04-02
            • 2014-10-08
            • 2021-08-10
            • 1970-01-01
            • 2017-12-24
            相关资源
            最近更新 更多