2016-09-28 23 views
0

我有一大塊文字。它有換行符,但由於換行符仍然很長,所以換行符會換行。由於所有其他腳本函數的所有行都縮進了一個空格,所以我希望能夠匹配它。我知道,如果我只打印一行,我可以插入一個空格,如果我想在符合一行的換行符後縮進,我可以在它後面插入一個空格\n縮進控制檯中的新行

如何讓文本塊中的每一行縮進? e.g:

text = """This is a block of text. It keeps going on and on and on. It has some line breaks \n but mostly just keeps going on without breaks. The lines are sometimes too long, so they wrap to the next line, but they don't indent. I need to fix this"""

,將打印爲:

>>> print(text) 
    This is a block of text. It keeps going on 
    and on and on. It has some line breaks 

    but mostly just keeps going on without 
    breaks. The lines are sometimes too long, 
    so they wrap to the next line, but they 
    don't indent. I need to fix this 

回答

0

這是你在找什麼?

import textwrap 
from string import join, split 

text = """This is a block of text. It keeps going on 
      and on and on. It has some line breaks \n 
      but mostly just keeps going on without 
      breaks. The lines are sometimes too long, 
      so they wrap to the next line, but they 
      don't indent. I need to fix this""" 

print "\nPrinted as one line:\n" 
t=join(text.split()) 
print t 

print "\nPrinted as formatted paragraph:\n" 
t=join(text.split()) 
t=textwrap.wrap(t,width=70,initial_indent=' '*4,subsequent_indent=' '*8) 
t=join(t,"\n") 
print t 

結果:

Printed as one line:                                   

This is a block of text. It keeps going on and on and on. It has some line breaks but mostly just keeps going on without breaks. The lines are sometimes too lo 
ng, so they wrap to the next line, but they don't indent. I need to fix this                     

Printed as formatted paragraph:                                 

    This is a block of text. It keeps                               
     going on and on and on. It has                               
     some line breaks but mostly just                              
     keeps going on without breaks.                               
     The lines are sometimes too                                
     long, so they wrap to the next                               
     line, but they don't indent. I                               
     need to fix this                                  
+0

我無法導入連接或上層 – user6896502

+0

@NateHailfire,您運行的是哪個版本的python? – blackpen

0

你說的加入,分裂是不能進口。請嘗試以下操作:

import re, textwrap 

def myformatting(t): 
    t=re.sub('\s+',' ',t); t=re.sub('^\s+','',t); t=re.sub('\s+$','',t) 
    t=textwrap.wrap(t,width=40,initial_indent=' '*4,subsequent_indent=' '*8) 
    s="" 
    for i in (t): s=s+i+"\n" 
    s=re.sub('\s+$','',s) 
    return(s) 

text = """\t\tThis is a block of text. It keeps going on 
      and on and on. It has some line breaks \n 
      but mostly just keeps going on without 
      breaks. The lines are sometimes too long, 
      so they wrap to the next line, but they 
      don't indent. I need to fix this""" 

text=myformatting(text) 
print text