国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

每日一“酷”之textwrap

2019-11-14 17:34:39
字體:
來源:轉載
供稿:網友

介紹:需要美觀打印時,可以使用textwrap模塊來格式化要輸出的文本,這個模塊允許通過編程提高類似段落自動換行或填充特性等功能。

1 創建實例數據

1 sample_text = '''2     I’m very happy and I like to make friends with others. 3     I  also like singing but traveling is my favorite,   I have been to  many interesting places in China but I haven’t been to other  countries. 4     What a pity!At school,    I study Chinese,math, English, history, politics  and so on. I like all of them. 5     I often help my teacher take   care of my class and I think I am a good helper. 6     I live  with my parents and we go home on time every day.7     '''

創建 testwrap_example.py 文件 其中保存 sample_text 這段文本信息
2 填充段落

1 import textwrap2 from testwrap_example import sample_text3 PRint 'No dedent: /n'4 print textwrap.fill(sample_text, width=50)

運行結果:

現在的狀況是左對齊,只有第一行保留了縮進,其余各行前面的恐嚇則嵌入到了段落中。

3、去除現有縮進

1 import textwrap2 from testwrap_example import sample_text3 dedented_text = textwrap.dedent(sample_text)4 print 'Dedented: /n'5 print dedented_text

運行結果:

由于“dedent(去除縮進)”與“indent(縮進)”正好相反,因此這里的結果是得到一個文本框,而且刪除各行最前面的空白處。如果莫一行比其他行鎖緊更多,曾輝有一些空白符未刪除。即使:

執行前(!代表空格):

!aaa

!!!aaa

!bbb

執行后:

aaa

!!aaa

bbb

4、結合dedent 和 fill

現在講去除縮進的文本傳入到fill(),并提供一組不同的wideh值(改值控制顯示的寬度) 

1 import textwrap2 from testwrap_example import sample_text3 dedented_text = textwrap.dedent(sample_text).strip()4 for width in [45,70]:5     print '%d  Columns:/n' % width6     print textwrap.fill(dedented_text, width=width)7     print 

運行結果:

5、懸掛縮進

不僅輸出的寬度可以設置,還可以單獨控制第一行的縮進,以區分后面行

1 import textwrap2 from testwrap_example import sample_text3 dedented_text = textwrap.dedent(sample_text).strip()4 print textwrap.fill(dedented_text, 5                     initial_indent = '',6                     subsequent_indent = '*'*4,7                     width =75 )

運行結果:

這樣一來會生成已走過懸掛縮進,即第一行與其他行不同;縮進可以包含空格和其他非空白字符


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 陆河县| 抚松县| 建瓯市| 罗源县| 赤峰市| 巢湖市| 三门峡市| 武陟县| 福海县| 武隆县| 驻马店市| 神池县| 云霄县| 苏尼特右旗| 特克斯县| 略阳县| 观塘区| 普兰县| 柞水县| 沧源| 高青县| 神木县| 睢宁县| 恩平市| 温泉县| 舟山市| 南宁市| 静宁县| 罗田县| 汕尾市| 云安县| 禹城市| 翼城县| 若羌县| 金昌市| 五寨县| 云和县| 阜新市| 上犹县| 天峻县| 手游|