Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python split string with Nth occurrence of a character

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']

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading