如何使用print()包装和缩进长行?
我正在用Python从一个网络服务获取数据。这些数据是一个列表,最后会展示给用户。我已经让它打印出来像这样:
( 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 个回答
11
使用 textwrap 模块:http://docs.python.org/library/textwrap.html
textwrap.fill(text, initial_indent='', subsequent_indent=' ')