- Python進階編程:編寫更高效、優雅的Python代碼
- 劉宇宙 謝東 劉艷
- 248字
- 2021-04-30 12:39:38
2.2.7 字符串格式化
我們在工作過程中有時會有以指定的列寬將長字符串重新格式化的需求,此時可使用textwrap模塊來格式化長字符串的輸出。相關代碼(str_format.py)示例如下:
test_str = "PyCons take place throughout many parts of the world. \ Each PyCon is different in its own way; drawing from its \ own geographical location as well as local history and culture. \ In 2017 another beautiful country opened its doors to a new PyCon, \ with the launch of PyCon Colombia. "
使用textwrap格式化字符串的多種方式(str_format.py)如下:
import textwrap print(textwrap.fill(test_str, 70)) print(textwrap.fill(test_str, 40)) print(textwrap.fill(test_str, 40, initial_indent=' ')) print(textwrap.fill(test_str, 40, subsequent_indent=' '))
textwrap模塊對于字符串打印是非常有用的,特別是當希望輸出自動匹配終端大小的時候。我們可以使用os.get_terminal_size()方法來獲取終端的大小,示例如下:
import os print(os.get_terminal_size().columns)
fill()方法可接收一些其他可選參數來控制tab、語句結尾等。
推薦閱讀
- Game Programming Using Qt Beginner's Guide
- Python爬蟲開發:從入門到實戰(微課版)
- 編程卓越之道(卷3):軟件工程化
- 跟小海龜學Python
- 從學徒到高手:汽車電路識圖、故障檢測與維修技能全圖解
- Nexus規模化Scrum框架
- 編程數學
- 執劍而舞:用代碼創作藝術
- Unity 2018 Augmented Reality Projects
- Java Web應用開發項目教程
- PostgreSQL Developer's Guide
- Learning C# by Developing Games with Unity 3D Beginner's Guide
- Elixir Cookbook
- Practical C Programming
- Learn iOS 11 Programming with Swift 4(Second Edition)