【问题标题】:How to wrap and indent long lines when using print()?使用 print() 时如何换行和缩进长行?
【发布时间】:2010-12-04 18:24:28
【问题描述】:

我正在使用 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

有什么想法如何打印上面的行而不手动分解行吗?

【问题讨论】:

    标签: python printing indentation


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-06
      • 2015-12-19
      • 2013-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-27
      相关资源
      最近更新 更多