# 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) -> list:
l = []  # New list
temp = ""  # temp value
count = 0  # Counter, that get will be reset, each time the temp gets 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 >= 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) -> 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']

• This fails for n != 2, because then the tuple unpacking in your return line does not work anymore. Commented Mar 9, 2020 at 8:12
• @Graipher, fixed Commented Mar 9, 2020 at 14:28
• Now the last sentence is not true anymore, but otherwise, nice! Commented Mar 9, 2020 at 14:30

You can simply take advantage from builtin range(start, stop[, step]) and collect the needed chunks passing input n size as range's step parameter:

def split_nth(inp_str: str, sep: str, n: int = 2) -> list:
chunks = inp_str.split(sep)
return [sep.join(chunks[i: i + n]) for i in range(0, len(chunks), n)]

print(split_nth("25:hellwdasd:64:da:12:yeah:1:y", ":", 3))


The output:

['25:hellwdasd:64', 'da:12:yeah', '1:y']
`