《Python Cookbook 3rd》笔记(2.16):以指定列宽格式化字符串
生活随笔
收集整理的這篇文章主要介紹了
《Python Cookbook 3rd》笔记(2.16):以指定列宽格式化字符串
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
以指定列寬格式化字符串
問題
你有一些長字符串,想以指定的列寬將它們重新格式化。
解法
使用 textwrap 模塊來格式化字符串的輸出。比如,假如你有下列的長字符串:
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."下面演示使用 textwrap 格式化字符串的多種方式:
>>> import textwrap >>> print(textwrap.fill(s, 70)) 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(textwrap.fill(s, 40)) 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(textwrap.fill(s, 40, 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.>>> print(textwrap.fill(s, 40, subsequent_indent=' ')) Look into my eyes, look into my eyes,the eyes, the eyes, the eyes, notaround the eyes, don't look aroundthe eyes, look into my eyes, you'reunder.討論
textwrap 模塊對于字符串打印是非常有用的,特別是當你希望輸出自動匹配終端大小的時候。你可以使用 os.get terminal size() 方法來獲取終端的大小尺寸。比如:
>>> import os >>> os.get_terminal_size().columns 80 >>>fill() 方法接受一些其他可選參數來控制tab,語句結尾等。 參閱 textwrap.TextWrapper 文檔 獲取更多內容。
總結
以上是生活随笔為你收集整理的《Python Cookbook 3rd》笔记(2.16):以指定列宽格式化字符串的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 算法(11)-leetcode-expl
- 下一篇: 机器学习算法分类总结