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,472
  • 5
  • 17
  • 35
  • 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
  • 176,452
  • 29
  • 245
  • 321