2016-09-12 249 views
0

格式化我有一個Python腳本,看起來像這樣:字符串在輸出

print "Header 1" 
    print "\t Sub-header 1" 
    print "\t\t (*) Sentence 1 begins here and goes on... and ends here." 

的句子被印刷在與同類格式的環路,它給終端這樣的輸出:

Header 1 
    Sub-header 1 
     (*) Sentence 1 begins here and goes on... 
and ends here. 
     (*) Sentence 2 begins here and goes on ... 
and ends here. 
     . 
     . 
     . 

有什麼辦法可以使格式如下? :

Header 1 
    Sub-header 1 
     (*) Sentence 1 begins here and goes on... 
      and ends here. 
     (*) Sentence 2 begins here and goes on ... 
      and ends here. 
     . 
     . 
     . 
+1

我使用print'print'('Text_1 =%-20s | Text_2 =%0s | Text_3 =%6s \ n')%('Here','Here_2','Here_3')'在屏幕上打印。這對你有幫助嗎? (運行它) – SnuKies

+2

確實有一種方法可以根據需要進行格式設置,但正確的方法可能取決於您現有的代碼。你能解釋一下這個格式是如何完成的嗎? – Tryph

+0

@SnuKies:謝謝,但對我的情況沒有幫助。由於句子太長,格式仍然在終端中斷。 –

回答

1

textwrap模塊的幫助下,它可以很容易實現:

import textwrap 

LINE_LENGTH = 80 
TAB_LENGTH = 8 


def indent(text, indent="\t", level=0): 
    return "{}{}".format(indent * level, text) 

def indent_sentence(text, indent="\t", level=0, sentence_mark=" (*) "): 
    indent_length = len(indent) if indent != "\t" else TAB_LENGTH 
    wrapped = textwrap.wrap(text, 
          LINE_LENGTH 
          - indent_length * level 
          - len(sentence_mark)) 
    sentence_new_line = "\n{}{}".format(indent * level, " " * len(sentence_mark)) 
    return "{}{}{}".format(indent * level, 
          sentence_mark, 
          sentence_new_line.join(wrapped)) 


print indent("Header 1") 
print indent("Sub-header 1", level=1) 
print indent_sentence("Sentence 1 begins here and goes on... This is a very " 
         "long line that we will wrap because it is nicer to not " 
         "have to scroll horizontally. and ends here.", 
         level=2) 

它打印這個在Windows控制檯,選項卡是8個字符長:

Header 1 
     Sub-header 1 
       (*) Sentence 1 begins here and goes on... This is a very long 
        line that we will wrap because it is nicer to not have to 
        scroll horizontally. and ends here. 
+0

謝謝!這正是我期待的! –