Split string at nth occurrence of a given character

后端 未结 7 1984
攒了一身酷
攒了一身酷 2020-11-30 05:50

Is there a Python-way to split a string after the nth occurrence of a given delimiter?

Given a string:

\'20_231_myString_234\'

It s

7条回答
  •  北荒
    北荒 (楼主)
    2020-11-30 06:17

    I had a larger string to split ever nth character, ended up with the following code:

    # Split every 6 spaces
    n = 6
    sep = ' '
    n_split_groups = []
    
    groups = err_str.split(sep)
    while len(groups):
        n_split_groups.append(sep.join(groups[:n]))
        groups = groups[n:]
    
    print n_split_groups
    

    Thanks @perreal!

提交回复
热议问题