你有一些长字符串,想以指定的列宽将它们从新格式化。html
使用textwrap
模块的fill
或wrap
函数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()
来获得终端的宽度,而后传给width
htm
>>> textwrap.fill(s, width=os.get_terminal_size().columns)
此外,当咱们须要格式化的次数不少时,更高效的方法是先建立一个TextWrapper
对象,设置好width
、initial_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每日一练