Split string at nth occurrence of a given character

后端 未结 7 1958
攒了一身酷
攒了一身酷 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:09

    I like this solution because it works without any actuall regex and can easiely be adapted to another "nth" or delimiter.

    import re
    
    string = "20_231_myString_234"
    occur = 2  # on which occourence you want to split
    
    indices = [x.start() for x in re.finditer("_", string)]
    part1 = string[0:indices[occur-1]]
    part2 = string[indices[occur-1]+1:]
    
    print (part1, ' ', part2)
    

提交回复
热议问题