Python每日一练0017

问题

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

解决方案

使用textwrap模块的fillwrap函数

假设有一个很长的字符串

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

我们可以使用fill函数来将这个长字符串自动切分为若干短字符串,只需要指定width即可

>>> print(textwrap.fill(s, width=60))
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.

也可以使用wrap函数,但是效果是一样的,只不过wrap函数返回的是一个列表而不是字符串

我们也可以指定其他一些参数比如initial_indent来设置段落的缩进,更多参数见讨论部分的链接

>>> print(textwrap.fill(s, width=60, 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.

讨论

如果希望能匹配终端的大小的话,我们可以使用os.get_terminal_size()来得到终端的宽度,然后传给width

>>> textwrap.fill(s, width=os.get_terminal_size().columns)

此外,当我们需要格式化的次数很多时,更高效的方法是先创建一个TextWrapper对象,设置好widthinitial_indent等等参数,然后再调用fill或者wrap方法

>>> wrap = textwrap.TextWrapper(width=60, initial_indent='    ')
>>> print(wrap.fill(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.

关于TextWrapper的其他参数见:

https://docs.python.org/3/library/textwrap.html

来源

Python Cookbook

关注

欢迎关注我的微信公众号:python每日一练

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值