Python每日一练0017

问题

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

解决方案

使用textwrap模块的fillwrap函数python

假设有一个很长的字符串微信

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

若是直接输出的话,可读性会比较差app

>>> 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函数返回的是一个列表而不是字符串spa

咱们也能够指定其余一些参数好比initial_indent来设置段落的缩进,更多参数见讨论部分的连接code

>>> 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()来获得终端的宽度,而后传给widthhtm

>>> 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的其余参数见:rem

https://docs.python.org/3/lib...

来源

Python Cookbook

关注

欢迎关注个人微信公众号:python每日一练

相关文章
相关标签/搜索