Split string at nth occurrence of a given character

后端 未结 7 1952
攒了一身酷
攒了一身酷 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 05:57

    Using re to get a regex of the form ^((?:[^_]*_){n-1}[^_]*)_(.*) where n is a variable:

    n=2
    s='20_231_myString_234'
    m=re.match(r'^((?:[^_]*_){%d}[^_]*)_(.*)' % (n-1), s)
    if m: print m.groups()
    

    or have a nice function:

    import re
    def nthofchar(s, c, n):
        regex=r'^((?:[^%c]*%c){%d}[^%c]*)%c(.*)' % (c,c,n-1,c,c)
        l = ()
        m = re.match(regex, s)
        if m: l = m.groups()
        return l
    
    s='20_231_myString_234'
    print nthofchar(s, '_', 2)
    

    Or without regexes, using iterative find:

    def nth_split(s, delim, n): 
        p, c = -1, 0
        while c < n:  
            p = s.index(delim, p + 1)
            c += 1
        return s[:p], s[p + 1:] 
    
    s1, s2 = nth_split('20_231_myString_234', '_', 2)
    print s1, ":", s2
    

提交回复
热议问题