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

Given "aaa-bbb-ccc-ddd-eee-fff" change every 2nd "-" to "+" → "aaa-bbb+ccc-ddd+eee-fff"

In a Python script I’m working on, I have a string

s = "aaa-bbb-ccc-ddd-eee-fff-ggg-hhh-iii-jjj-kkk-lll-mmm-nnn-ooo-ppp-qqq-rrr-sss"

where I want to change every second occurrence of "-" to "+" (or maybe every third, fourth, etc. occurrence or, in other words, I’d prefer a generic solution).

Is it possible to do what I want with a single regexp substitution, or have I to parse the string "manually"?

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

>Solution :

A little list comprehension could do this quickly:

print(''.join([x + ('+' if (i+1)%2==0 else '-') for i, x in enumerate(s.split('-'))])[:-1])
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