textwrap模块

方法

  textwrap.wrap(text,[width[,…]])   

import textwrap
sample_text = '''aaabbbcccdddeeeedddddfffffggggghhhhhhkkkkkkk'''
sample_text2 = '''aaa bbb ccc ddd eeee ddddd fffff ggggg hhhhhh kkkkkkk'''

print(sample_text)
print(textwrap.wrap(sample_text,width=5))
print(textwrap.wrap(sample_text2,width=5))
功能类似于拆分,但是也要考虑空格

  testwrap.fill(text,[width])

import textwrap
sample_text = '''aaabbbcccdddeeeedddddfffffggggghhhhhhkkkkkkk'''
sample_text2 = '''aaa bbb ccc ddd eeee ddddd fffff ggggg hhhhhh kkkkkkk'''

print(sample_text)
print(textwrap.fill(sample_text,width=5))
print(textwrap.fill(sample_text2,width=5))
功能和wrap类似,但是把列表拆成了空行

   textwrap.dedent(text) 

import textwrap
sample_text = '''
    aaabbb
                cccdddee    eedddddfffffggggghhhhhhkkkkkkk'''

print(textwrap.dedent(sample_text))
功能:去多余空格

属性

通过构造函数直接初始化

TextWrapper(initial_indent="* ")

或初始化后赋值

textWrap = textwrap.TextWrapper() textWrap.expand_tabs = True

属性如下:

width:宽度默认为70

expand_tabs:默认为true,如果设置为true,那么字符串里的所有制表符都会被变成空格,相当于用了字符串方法的expandtabs()。

replace_whitespace:如果设置为true,那么就会把字符串中的空白符转化为空格。 

drop_whitespace:默认true,如果设置为true,则每行开头和结尾的空白符都会被去掉,如果要去掉的空白符占据了整行,那么就会把整行去掉。 

initial_indent:在第一行开头插入指定字符串

subsequent_indent:除了第一行在每一行开头插入指定字符串

fix_sentence_endings:默认为false,如果为true,那么就会试图检查每个句子的结尾是两个空格分割,这个只在等宽字体里被需要。但是这个检查的算法是有缺陷的,它假设了句子是以.!?等这些字符为结尾。

break_long_words:默认为true,切断长句子来让每行的数据宽度都小于width。 

break_on_hyphens:连字符相关,默认true 

原文地址:https://www.cnblogs.com/yxi-liu/p/8550572.html