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])app

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) ide

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

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

 

屬性

經過構造函數直接初始化函數

TextWrapper(initial_indent="* ")字體

或初始化後賦值spa

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

 

屬性以下:blog

width:寬度默認爲70字符串

expand_tabs:默認爲true,若是設置爲true,那麼字符串裏的全部製表符都會被變成空格,至關於用了字符串方法的expandtabs()。string

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 

相關文章
相關標籤/搜索