Python-CookBook:35、以固定的列数重新格式化文本

本贴最后更新于 1703 天前,其中的信息可能已经事过境迁

问题

我们有一些很长的字符串,想将它们重新格式化,使得它们能按照用户指定的列数来显示。

解决方案

可以使用 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 模块以多种方式来重新格式化字符串:

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

print(s)
print()

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

print(textwrap.fill(s,40))
print()

print(textwrap.fill(s,40,initial_indent=' '))
print()

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.

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.

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.

 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.

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()方法还有一些额外的选项可以用来控制如何处理制表符、句号等。请参阅 textwrap.TextWrapper 类的文档(http://docs.python.org/3.3/library/ textwrap. html# text w r ap.TextWrapper)以获得进一步的细节。

  • Python

    Python 是一种面向对象、直译式电脑编程语言,具有近二十年的发展历史,成熟且稳定。它包含了一组完善而且容易理解的标准库,能够轻松完成很多常见的任务。它的语法简捷和清晰,尽量使用无异义的英语单词,与其它大多数程序设计语言使用大括号不一样,它使用缩进来定义语句块。

    535 引用 • 672 回帖 • 1 关注
  • 书籍

    宋真宗赵恒曾经说过:“书中自有黄金屋,书中自有颜如玉。”

    76 引用 • 390 回帖 • 1 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...