0

what is the pythonic efficient way to insert a character every n-characters in a string? for example

ins("aabbccdd", 2, "-") => "aa-bb-cc-dd"

is there a way to do this with iterators?

lgd
  • 1,412
  • 4
  • 16
  • 34
  • possible duplicate of [Pythonic way to insert every 2 elements in a string](http://stackoverflow.com/questions/3258573/pythonic-way-to-insert-every-2-elements-in-a-string) – l'L'l Mar 02 '15 at 03:34

1 Answers1

4

You can str.join i length chunks of s:

s = "aabbccdd"
i = 2
print("-".join([s[j:j+i] for j in range(0,len(s),i)]))
aa-bb-cc-dd
Padraic Cunningham
  • 168,988
  • 22
  • 228
  • 312