Python每日一練0017
阿新 • • 發佈:2019-01-24
問題
你有一些長字串,想以指定的列寬將它們重新格式化。
解決方案
使用textwrap
模組的fill
或wrap
函式
假設有一個很長的字串
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
物件,設定好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
的其他引數見:
來源
Python Cookbook
關注
歡迎關注我的微信公眾號:python每日一練