Train Heartnet
Train Heartnet

Reputation: 825

String formatting in output

I have a python script that looks like this:

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

The sentences are being printed in a loop with the similar format, and it gives an output like this in the terminal:

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.
         .
         .
         .

Is there any way I can make the formatting as follows? :

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.
         .
         .
         .

Upvotes: 0

Views: 116

Answers (1)

Tryph
Tryph

Reputation: 6219

with the help of the textwrap module, it could be done quite easily:

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)

It prints this in a Windows console where tab are 8 chars long:

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.

Upvotes: 1

Related Questions