1

I want be able to add a plus sign (+) for every third letter. For instance,

sequence = ABCDEF

ABC + DEF

I've tried Str.join and it works sorta, but I want it to add a plus sign every third letter.

This is what I have so far.

s = sequence
a = (' + '.join(s))
  • 1
    You could use a chunking solution from here: [How do you split a list into evenly sized chunks?](https://stackoverflow.com/q/312443/4518341) Most of them work on any sequence including strings. – wjandrea Feb 28 '20 at 22:44
  • 1
    You might want to have a look to https://stackoverflow.com/questions/3258573/pythonic-way-to-insert-every-2-elements-in-a-string – J Faucher Feb 28 '20 at 22:46

2 Answers2

3

You could try something like this:

'+'.join(sequence[i:i+3] for i in range(0,len(sequence),3))

Basically what this does is, first, get a sequence of numbers at indices at multiples of 3 using range: range(0,len(sequence),3)

Next, find substrings of length 3 starting from every index: [sequence[i, i+3] for i in range...]

Finally, join these substrings with a '+': '+'.join(...)

Hope this helps.

mousetail
  • 7,009
  • 4
  • 25
  • 45
0
''.join([your_string[n] if n%3 != 2 else your_string[n]+' + ' for n in range(len(your_string))])

A bit more complicated than the previous answer, but basically it creates a string where every character is the same as the original string, except for every third one, to which it gets added ' + '.

PMM
  • 366
  • 1
  • 10