【Python Cookbook】S02E14 以固定的列数重新格式化文本 —— textwrap.fill(text, width, subsequent_indent=)

问题

我们有一些很长很长的字符串,我们希望能够将其重新格式化,按照用户制定的列数来显示。

解决方案

推荐使用 textwrap 模块,下述案例中使用 textwrap.fill(text, width) 函数,其中的两个参数 text 为长文本内容,width 为每一行的长度。

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

import textwrap

print(textwrap.fill(s, 70))
print("-" * 20)
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.
--------------------
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.

对于需要在第二行开始前加入空格的,可增加参数 subsequent_indent

print(textwrap.fill(s, 70))
print("*"*20, "添加参数后", "*"*20)
print(textwrap.fill(s, 70, 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.

讨论

textwrap 模块能够以简单直接的方式对文本格式做整理使其适合与设备大小展示内容。结合到实际应用中,其可以通过 os.get_terminal_size() 来获取终端的大小

import os

size = os.get_terminal_size().columns

关于 textwrap.fill() 的更多用法,请参阅 textwrap.TextWrapper 类文档获取更多技术细节。

  • 12
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

脚踏实地的大梦想家

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值