VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • python模块学习- textwrap 文本包装和填充

python模块学习- textwrap 文本包装和填充

代码实例:

sample_text = '''

   The textwrap module can beused to format text for output in

   situations wherepretty-printing is desired.  It offers

   programmatic functionalitysimilar to the paragraph wrapping

   or filling features found inmany text editors.

'''

段落填充:

1
2
3
4
5
import textwrap
from textwrap_exampleimport sample_text
  
print 'Nodedent:\n'
printtextwrap.fill(sample_text, width=50)

 

执行结果:

# pythontextwrap_fill.py

No dedent:

 

    The textwrap module can be used to format

text for outputin     situations where pretty-

printing is desired.  It offers    programmatic

functionalitysimilar to the paragraph wrapping

or fillingfeatures found in many text editors.

结果为左对齐,第一行有缩进。行中的空格继续保留。

移除缩进:

1
2
3
4
5
6
import textwrap
fromtextwrap_exampleimport sample_text
  
dedented_text= textwrap.dedent(sample_text)
print 'Dedented:'
printdedented_text

 

执行结果:

# pythontextwrap_dedent.py

Dedented:

 

The textwrapmodule can be used to format text for output in

situations wherepretty-printing is desired.  It offers

programmaticfunctionality similar to the paragraph wrapping

or fillingfeatures found in many text editors.

这样第一行就不会缩进。

结合移除缩进和填充:

1
2
3
4
5
6
7
8
import textwrap
fromtextwrap_exampleimport sample_text
  
dedented_text=textwrap.dedent(sample_text).strip()
for widthin [45,70 ]:
       print '%d Columns:\n' % width
       print textwrap.fill(dedented_text,width=width)
       print

 

执行结果:

# pythontextwrap_fill_width.py

45 Columns:

 

The textwrapmodule can be used to format

text for output insituations where pretty-

printing isdesired.  It offers programmatic

functionalitysimilar to the paragraph

wrapping orfilling features found in many

text editors.

 

70 Columns:

 

The textwrapmodule can be used to format text for output in

situations wherepretty-printing is desired.  It offersprogrammatic

functionality similarto the paragraph wrapping or filling features

found in many texteditors.

悬挂缩进:悬挂缩进第一行的缩进小于其他行的缩进。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import textwrap
fromtextwrap_exampleimport sample_text
  
dedented_text=textwrap.dedent(sample_text).strip()
printtextwrap.fill(dedented_text,
                    initial_indent='',
                    subsequent_indent=' ' * 4,
                    width=50,
                    )
       执行结果:
# pythontextwrap_hanging_indent.py
The textwrapmodule can be used toformat textfor
    outputin situations where pretty-printingis
    desired. It offers programmatic functionality
    similar to the paragraph wrapping orfilling
    features foundin many text editors.

相关教程