将字符串拆分为每个第n个字符,并使用不同的分隔符将其重新连接

2024-09-24 22:23:40 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

这是我第一次尝试使用.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.'

然后,我在分离器内尝试了一个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.'

也许结合.split().join()函数可以更好地完成我想做的事情,但我找不到方法。请问,你对如何做到这一点有什么想法吗


Tags: tothatherepartyextensionscontentarelike
3条回答

这里有一条你可以试试的单行线:

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

Wrap为您提供文本的可编辑部分。如果可以使用分隔符创建iterable,则可以使用"".join(t for pair in zip(wrapped_chunks, separators) for t in pair)将其连接起来

您可以使用无限生成器创建分隔符:

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

这将给您一个过多的分隔符,因此您可能希望删除它或特别附加wrapped_chunks的最后一项

如果您想在几个不同的分隔符之间切换,您可以使用itertools.cycle(["SEP1", "SEP2", "SEP3"])来生成重复的令牌循环

试试这个:

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.

相关问题 更多 >