输出中的字符串格式

时间:2016-09-12 08:00:25

标签: python python-2.7 formatting string-formatting

我有一个如下所示的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 个答案:

答案 0 :(得分: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控制台中打印出来,其中tab为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.