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?

1

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

'-'.join(s[i:i+2] for i in range(0, len(s), 2)) can eliminate the i = 2.
@I'L'I I used i so the OP can choose the chunk size

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.