-2

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

gboffi
  • 22,939
  • 8
  • 54
  • 85

1 Answers1

2

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])
JNevill
  • 46,980
  • 4
  • 38
  • 63