Search code examples
pythonregexpython-re

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"?


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