Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 918
prog-amateur Avatar asked Jan 26 '23 00:01

prog-amateur


1 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))])
like image 167
One Lyner Avatar answered Jan 28 '23 11:01

One Lyner