2016-09-28 24 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