Advertisements
I have a string having some comma separated values
Input text
my_string = 'abc,kjj,hg,kj,ls,jsh,ku,lo,sasad,hh,da'
I need to split this string with every 5th occurrence of comma
expected output: ['abc,kjj,hg,kj,ls','jsh,ku,lo,sasad,hh','da']
Code I tried
a = re.findall("\,".join(["[^,]+"] * 5), my_string)
Current Output
['abc,kjj,hg,kj,ls', 'jsh,ku,lo,sasad,hh']
How to get remaining string?
>Solution :
You can do it by splitting on , and joining in chunks:
seq = my_string.split(',')
size = 5
[','.join(seq[pos:pos + size]) for pos in range(0, len(seq), size)]
Output:
['abc,kjj,hg,kj,ls', 'jsh,ku,lo,sasad,hh', 'da']