国产探花免费观看_亚洲丰满少妇自慰呻吟_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 )

運行結果:

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


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 唐海县| 沁阳市| 德令哈市| 高碑店市| 鄱阳县| 河曲县| 贞丰县| 普兰县| 凭祥市| 阿城市| 万载县| 甘德县| 北票市| 宁都县| 宜都市| 南川市| 清新县| 永定县| 富阳市| 弋阳县| 通榆县| 五家渠市| 普安县| 磴口县| 黎平县| 绥芬河市| 大同市| 连云港市| 武功县| 绍兴市| 永顺县| 开化县| 南昌市| 安义县| 广东省| 铁岭市| 张家川| 昌都县| 临颍县| 磴口县| 巩义市|