Python3 - 以指定列宽格式化字符串

问题

对很长的字符串,以指定的列宽将它们重新格式化。

解决方案

使用 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."

输出时每行80个字符

import textwrap
print(textwrap.fill(s, 80))

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.

输出时每行40个字符

import textwrap
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.

首行缩进4个空格

import textwrap
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.

非首行缩进4个空格

import textwrap
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
print(os.get_terminal_size().columns)
80

你可能感兴趣的:(Python3 - 以指定列宽格式化字符串)