Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wrap and indent long lines when using print()?

I'm using Python to gather data from a Web service. The data itself is a list that will presented to users. I've managed it that it's printed out like:

( 1)  Example of strings
( 2)  Example 4
( 3)  Another Example
( 4)  Another Example 2

I'm using rjust (2) for the numbers. However, if the lines are very long, the printing will be like. The breaking width is the length of terminal (rxvt, gnome-terminal):

( 1)  Example of a very very very very long string and
that doesn't look fine
( 2)    Example of indented long line that is very very
long, example line
( 3)  Another Example
( 4)  Another Example of a very very long string and 
whatever here is

But what I've want is a print out like:

( 1)  Example of a very very very very long string and
      that doesn't look fine
( 2)    Example of indented long line that is very very
        long, example line
( 3)  Another Example
( 4)  Another Example of a very very long string and 
      whatever here is

Is there any ideas how to print the lines like above without breaking up the lines manually?

like image 976
Fatih Arslan Avatar asked Feb 25 '23 16:02

Fatih Arslan


1 Answers

Use the textwrap module: http://docs.python.org/library/textwrap.html

 textwrap.fill(text, initial_indent='', subsequent_indent='      ')
like image 54
Adam Vandenberg Avatar answered Mar 06 '23 21:03

Adam Vandenberg