Python - Split nth occurence of a character in string I needed this function for a project I'm currently working on. I think there is definitely a way to make this prettier and have tickle more performance out of it, but how?

def nthofchar(string: str, char: str, n: int = 2) -&gt; list:
    l = []  # New list
    temp = ""  # temp value
    count = 0  # Counter, that get will be reset, each time the temp get`s appended to the list

    for value in string.split(char):
        temp += value + char  # Add char to have it still in the string

        # Incrementing
        count += 1
        if count &gt;= n:
            l.append(temp[:len(char) * -1])  # Remove last char
            # Reset
            count = 0
            temp = ""

    return l



print(nthofchar("25:hellwdasd:64:da:12:yeah:1:y", ":", 2))
# Output: ['25:hellwdasd', '64:da', '12:yeah', '1:y']

print(nthofchar("1;a;2;b;3;c;4;d;5;e;6;f", ";", 2))
# Output: ['1;a', '2;b', '3;c', '4;d', '5;e', '6;f']
A python idiom for iterating over a sequence in groups it to use zip() like so:

group_iter = zip(*[iter(seq)]*n)


where seq is the sequence and n is the size of each group. Note that the last group will be dropped if it doesn't have n elements.

Using that idiom, your function could be coded:

def nthofchar(string: str, char: str, n: int = 2) -&gt; list:
    chunks = string.split(char)
    groups = zip(*[iter(chunks)]*n)

    return [char.join(group) for group in groups]


Added a test case for n != 2:

print(nthofchar("1;a;b;2;c;d;3;e;f;4;g;h;5;i;j;6;k;l", ";", 3))
# Output: ['1;a;b', '2;c;d', '3;e;f', '4;g;h', '5;i;j', '6;k;l']