1

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

graphs showing long text wrapped

Craig
  • 4,605
  • 1
  • 18
  • 28
Azabache
  • 21
  • 2
  • 1
    Does this answer your question? [split tick labels or wrap tick labels](https://stackoverflow.com/questions/57473450/split-tick-labels-or-wrap-tick-labels) – Trenton McKinney May 05 '20 at 18:04

2 Answers2

4

You can use textwrap:

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

End hunger, achieve food security and improved
nutrition and promote sustainable agriculture
Pygirl
  • 12,969
  • 5
  • 30
  • 43
1

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:

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))