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

巧了我就是萌 提交于 2019-12-10 15:44:42

问题


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?


回答1:


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

 textwrap.fill(text, initial_indent='', subsequent_indent='      ')


来源:https://stackoverflow.com/questions/4355061/how-to-wrap-and-indent-long-lines-when-using-print

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!