String formatting in output
<p>I have a python script that looks like this:</p>

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

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

<pre><code>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.
         .
         .
         .
</code></pre>

<p>Is there any way I can make the formatting as follows? :</p>

<pre><code>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.
         .
         .
         .
</code></pre>

<p>with the help of the <a href="https://docs.python.org/2/library/textwrap.html" rel="nofollow">textwrap</a> module, it could be done quite easily:</p>

<pre><code>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)
</code></pre>

<p>It prints this in a Windows console where tab are 8 chars long:</p>

<pre><code>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.
</code></pre>

python python-2.7 formatting string-formatting