介紹:需要美觀打印時,可以使用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 )
運行結果:

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