简体   繁体   English

如何打破 python 中的长字符串?

[英]How to break long strings in python?

I have a list of very long strings, and I want to know if theres any way to separate every string´s element by a certain number of words like the image on the bottom.我有一个很长的字符串列表,我想知道是否有任何方法可以将每个字符串的元素用一定数量的单词(如底部的图像)分开。

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”]

the final result is kinda like the image最终结果有点像图片

显示包裹的长文本的图表

You can use textwrap :您可以使用textwrap

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

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

If you want to break it in terms of number of words, you can:如果你想在字数方面打破它,你可以:

Split the string into a list of words:将字符串拆分为单词列表:

my_list = my_string.split()

Then you can break it into K chunks using numpy:然后您可以使用 numpy 将其分成 K 个块:

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

Then, to get a chunk back into a string, you can do:然后,要将块恢复为字符串,您可以执行以下操作:

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

Or to get all of them to strings, you can do:或者要将它们全部转换为字符串,您可以执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM