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每日一練

相關文章
相關標籤/搜索