Python 将字符串拆分为每个第n个字符,并使用不同的分隔符将其重新连接
我尝试用不同的分隔符在句子中使用文本换行。这正是我希望得到的输出:Python 将字符串拆分为每个第n个字符,并使用不同的分隔符将其重新连接,python,string,delimiter,word-wrap,Python,String,Delimiter,Word Wrap,我尝试用不同的分隔符在句子中使用文本换行。这正是我希望得到的输出: '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 allo
'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()
函数可以更好地完成我想做的事情,但我找不到方法。请问,您对如何实现这一点有什么想法吗?Wrap为您提供了文本的可编辑部分。如果你能用分隔符创建一个iterable,你可以用将它们连接起来。连接(t表示成对的zip(包装的块,分隔符)表示成对的t)
您可以使用无限生成器创建分隔符:
def inf_separators():
index = 1
while True:
yield f"SEPARATOR{index}"
index = index + 1
这将给您一个太多的分隔符,因此您可能需要删除它或附加最后一项包装的\u块
如果您想在几个不同的分隔符之间切换,可以使用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.
从文本包装导入包装
句子=''这里有像Scener这样的第三方扩展,允许我们观看内容。''
新的_句=“”
零件=包装(第20句)
对于i,列举部分(部分):
新句子+=部分
#除最后一个零件外,在每个零件后添加分隔符
如果i
这里有一个单行程序,您可以尝试:
text = ''.join([(f'[SEPARATOR{i}]' if i else '') + w
for i, w in enumerate(wrap(sentence, 20))])
我要感谢这里的每一个人。这个答案解决了我的问题,但是对于没有数字分隔符的人来说,如果分隔符是A、B、C而不是数字呢?我想我们不能使用
枚举
对吗?再次感谢。要回答我关于字符串分隔符的问题,请参阅@Gabip的答案。我也应该接受你的答案,因为它不仅解决了我的问题,而且解决了将分隔符作为字符串的人(如分隔符A、分隔符B等)的问题。非常感谢。