zoukankan      html  css  js  c++  java
  • 每日一“酷”之textwrap

    介绍:需要美观打印时,可以使用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 textwrap
    2 from testwrap_example import sample_text
    3 print 'No dedent: 
    '
    4 print textwrap.fill(sample_text, width=50)

    运行结果:

    现在的状况是左对齐,只有第一行保留了缩进,其余各行前面的恐吓则嵌入到了段落中。

    3、去除现有缩进

    1 import textwrap
    2 from testwrap_example import sample_text
    3 dedented_text = textwrap.dedent(sample_text)
    4 print 'Dedented: 
    '
    5 print dedented_text

    运行结果:

    由于“dedent(去除缩进)”与“indent(缩进)”正好相反,因此这里的结果是得到一个文本框,而且删除各行最前面的空白处。如果莫一行比其他行锁紧更多,曾辉有一些空白符未删除。即使:

    执行前(!代表空格):

    !aaa

    !!!aaa

    !bbb

    执行后:

    aaa

    !!aaa

    bbb

    4、结合dedent 和 fill

    现在讲去除缩进的文本传入到fill(),并提供一组不同的wideh值(改值控制显示的宽度) 

    1 import textwrap
    2 from testwrap_example import sample_text
    3 dedented_text = textwrap.dedent(sample_text).strip()
    4 for width in [45,70]:
    5     print '%d  Columns:
    ' % width
    6     print textwrap.fill(dedented_text, width=width)
    7     print 

    运行结果:

    5、悬挂缩进

    不仅输出的宽度可以设置,还可以单独控制第一行的缩进,以区分后面行

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

    运行结果:

    这样一来会生成已走过悬挂缩进,即第一行与其他行不同;缩进可以包含空格和其他非空白字符

  • 相关阅读:
    Steve Jobs 2005年于 Stanford University 毕业典礼上的演讲
    欧姆龙血糖仪HEA214换购备忘
    (转载)2011年高考作文之《时间在流逝》(安徽考生)
    2012年部分节假日安排(转载)
    乔布斯语录(转载)
    欢乐谷一日游
    上海公交投诉电话:12319
    中国公路“买路钱”应该怎么管?(转载)
    C#操作excel
    SQL Server数据库对列的操作
  • 原文地址:https://www.cnblogs.com/victroy/p/4014803.html
Copyright © 2011-2022 走看看