2.16 以指定列宽格�化字符串¶

问题¶

你有一些长字符串,想以指定的列宽将它们�新格�化。

解决方案¶

使用 textwrap 模��格�化字符串的输出。比如,�如你有下列的长字符串:

s = "Look into my eyes, look into my eyes, the eyes, the eyes, \
the eyes, not around the eyes, don't look around the eyes, \
look into my eyes, you're under."

下�演示使用 textwrap 格�化字符串的多�方�:

>>> import textwrap
>>> print(textwrap.fill(s, 70))
Look into my eyes, look into my eyes, the eyes, the eyes, the eyes,
not around the eyes, don't look around the eyes, look into my eyes,
you're under.

>>> print(textwrap.fill(s, 40))
Look into my eyes, look into my eyes,
the eyes, the eyes, the eyes, not around
the eyes, don't look around the eyes,
look into my eyes, you're under.

>>> print(textwrap.fill(s, 40, initial_indent='    '))
    Look into my eyes, look into my
eyes, the eyes, the eyes, the eyes, not
around the eyes, don't look around the
eyes, look into my eyes, you're under.

>>> print(textwrap.fill(s, 40, subsequent_indent='    '))
Look into my eyes, look into my eyes,
    the eyes, the eyes, the eyes, not
    around the eyes, don't look around
    the eyes, look into my eyes, you're
    under.

讨论¶

textwrap 模�对于字符串打�是�常有用的,特别是当你希望输出自动匹�终端大�的时候。 你�以使用 os.get_terminal_size() 方法�获�终端的大�尺寸。比如:

>>> import os
>>> os.get_terminal_size().columns
80
>>>

fill() 方法接�一些其他�选�数�控制tab,语�结尾等。 �阅 textwrap.TextWrapper文档 获�更多内容。