'How to wrap text to the next line in curses?

I am trying to display text files in the terminal using curses, but some lines of the file are larger than the size of my terminal. How can I wrap this overflowing text to the next line?

    def display(self):
        max_y, max_x = self.stdscr.getmaxyx()

        text_list = self.text.split("\n")

        for y in range(len(text_list)): 
            for x in range(len(text_list[y])):
                self.stdscr.addstr(y, x, text_list[y][x])


Solution 1:[1]

I suggest taking look at textwrap (it is part of standard library). Consider following example

import textwrap
text = '''This is first paragraph
This is second paragraph which is also longest
This is last paragraph'''
paras = text.splitlines()
lines = [j for i in paras for j in textwrap.wrap(i,width=25)]
print(lines)

output

['This is first paragraph', 'This is second paragraph', 'which is also longest', 'This is last paragraph']

Note: I used 25 as width for illustration purposes. I used nested comprehension to get flat list, as using textwrap.wrap on elements of list gives nested list (list of lists), you might elect other way to flatten such list.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daweo