使用print()时如何包装和缩进长行?

时间:2010-12-04 18:24:29

标签: python printing indentation

我正在使用Python从Web服务收集数据。数据本身是一个将呈现给用户的列表。我已经设法将它打印出来像:

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

我正在使用rjust(2)来表示数字。但是,如果线条很长,打印就会像。断开宽度是终端的长度(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

但我想要的是打印出像:

( 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

有没有想法如何打印上面的行而不用手动分割线?

1 个答案:

答案 0 :(得分:8)

使用textwrap模块:http://docs.python.org/library/textwrap.html

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