你有一些長字符串,想以指定的列寬將它們從新格式化。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每日一練