如何在python中断开长字符串?

2024-06-16 13:36:50 发布

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

我有一个非常长的字符串列表,我想知道是否有任何方法可以通过一定数量的单词(如底部的图像)来分隔每个字符串的元素

List = [“End extreme poverty in all forms by 2030”,
“End hunger, achieve food security and improved nutrition and promote sustainable agriculture”,
“Ensure healthy lives and promote well-being for all at all ages”,
“Ensure inclusive and equitable quality education and promote lifelong learning opportunities for all”,
 “Promote sustained, inclusive and sustainable economic growth, full and productive employment and decent work for all”]

Print(list)

Out:
“End extreme poverty in all forms by 2030”,

“End hunger, achieve food security and improved 
nutrition and promote sustainable agriculture”,

“Ensure healthy lives and promote well-being for all at all ages”,

“Ensure inclusive and equitable quality education and promote 
lifelong learning opportunities for all”,

 “Promote sustained, inclusive and sustainable economic growth, 
full and productive employment and decent work for all”]

最终的结果有点像图像

graphs showing long text wrapped


Tags: and字符串in图像forbyformsinclusive
2条回答

您可以使用textwrap

import textwrap
print(textwrap.fill(List[1], 50))

End hunger, achieve food security and improved
nutrition and promote sustainable agriculture

如果你想在字数上打破它,你可以:

将字符串拆分为单词列表:

my_list = my_string.split()

然后可以使用numpy将其分解为K个块:

import numpy as np
my_chunks = np.array_split(my_list , K) #K is number of chunks

然后,要将块恢复为字符串,可以执行以下操作:

my_string = " ".join(my_chunk[0])

或者,要将它们全部转换为字符串,可以执行以下操作:

my_strings = list(map(" ".join, my_chunks))

相关问题 更多 >