Split string each Nth character and join it back with different separators

Viewed 76

I try to use text wrapping in a sentence with different separators. This is exactly what I would like to get as an output:

'here are third-party[SEPARATOR1]extensions like[SEPARATOR2]Scener that allow us[SEPARATOR3]to watch content.'

Here is my first attempt with .join() and wrap(), unsuccessful:

[In] : 
sentence = '''here are third-party extensions like Scener that allow us to watch content.'''

separator = '[SEPARATOR]'

text = separator.join(wrap(sentence, 20))

[Out] :
'here are third-party[SEPARATOR]extensions like[SEPARATOR]Scener that allow us[SEPARATOR]to watch content.'

Then, I have tried a for loop inside the separator, but without success too... :

[In] : 
sentence = '''here are third-party extensions like Scener that allow us to watch content.'''

for i in range(1, 4):
    separator = '[SEPARATOR' + str(i) + ']'

text = separator.join(wrap(sentence, 20))

[Out] :
'here are third-party[SEPARATOR3]extensions like[SEPARATOR3]Scener that allow us[SEPARATOR3]to watch content.'

Maybe combining .split() and .join() function can be a better way to do what I would like, but I can't find how. Please, do you have any idea about how to achieve this?

3 Answers

Here's a one liner you can try:

text = ''.join([(f'[SEPARATOR{i}]' if i else '') + w
                for i, w in enumerate(wrap(sentence, 20))])

Wrap gives you an iterable of your text. If you can create an iterable with your separators you can join them with "".join(t for pair in zip(wrapped_chunks, separators) for t in pair)

You can create your separators with an infinite generator:

def inf_separators():
    index = 1
    while True:
        yield f"SEPARATOR{index}"
        index = index + 1

This will give you one separator too many so you might want to delete it or append the last item of wrapped_chunks specially.

If you want to alternate between a few different separators you can use itertools.cycle(["SEP1", "SEP2", "SEP3"]) to generate a repetitive cycle of tokens.

Try this:

from textwrap import wrap

sentence = '''here are third-party extensions like Scener that allow us to watch content.'''

new_sentence = ""
parts = wrap(sentence, 20)
for i, part in enumerate(parts):
    new_sentence += part
    # adding separator after each part except for the last one
    if i < len(parts) - 1:
        new_sentence += f"[SEPARATOR{i+1}]"
print(new_sentence)

# output: here are third-party[SEPARATOR1]extensions like[SEPARATOR2]Scener that allow us[SEPARATOR3]to watch content.

Related