官术网_书友最值得收藏!

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、語句結尾等。

主站蜘蛛池模板: 古蔺县| 富裕县| 桂东县| 南木林县| 犍为县| 永康市| 大荔县| 基隆市| 鸡西市| 东方市| 左贡县| 兴业县| 金湖县| 霍林郭勒市| 闽清县| 利辛县| 隆化县| 琼结县| 搜索| 平果县| 遵化市| 宜宾县| 东乌珠穆沁旗| 迁安市| 郑州市| 临汾市| 祁门县| 西贡区| 芮城县| 昔阳县| 吉安县| 旌德县| 调兵山市| 余干县| 清河县| 平顶山市| 静乐县| 忻州市| 定结县| 库伦旗| 瓮安县|