拆分每个第 N 个字符的字符串,并使用不同的分隔符将其连接回来

pro*_*eur 4 python string delimiter word-wrap

我尝试在具有不同分隔符的句子中使用文本换行。这正是我想作为输出得到的:

'here are third-party[SEPARATOR1]extensions like[SEPARATOR2]Scener that allow us[SEPARATOR3]to watch content.'
Run Code Online (Sandbox Code Playgroud)

这是我第一次尝试.join()wrap(),不成功:

[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.'
Run Code Online (Sandbox Code Playgroud)

然后,我在分隔符内尝试了 for 循环,但也没有成功......:

[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.'
Run Code Online (Sandbox Code Playgroud)

也许结合.split().join()函数可以是做我想做的更好的方法,但我找不到如何做。请问,您对如何实现这一目标有任何想法吗?

小智 5

这是您可以尝试的单衬:

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