Python create indented string from a list
<p>I have a list of table of contents that I'd like to create into an indented string</p>

<pre><code>list = ['1. Section', '1.1 Subsection', '1.1.1 Subsubsection', '1.1.2 Subsubsection', '2. Section', '2.1 Subsection', '2.1.1 Subsubsection', '2.1.2 Subsubsection', '2.2 Subsection', '2.2.1 Subsubsection']
</code></pre>

<p>And the desired result is this:</p>

<pre><code>1. Section
    1.1 Subsection
        1.1.1 Subsubsection
        1.1.2 Subsubsection
2. Section
    2.1 Subsection
        2.1.1 Subsubsection
        2.1.2 Subsubsection
    2.2 Subsection
        2.2.1 Subsubsection
</code></pre>

<p>I've tried this:</p>

<pre><code>toc = ''

for tocitem in list:
    if re.match('(\d+)\.', tocitem):
        toc += tocitem + '\n'
    elif re.match('(\d+)\.(\d+)', tocitem):
        toc += '\t' + tocitem + '\n'
    else:
        toc += '\t\t' + tocitem + '\n'
</code></pre>

<p>But the tabs are not recognized, that is I get this</p>

<pre><code>1. Section
1.1 Subsection
1.1.1 Subsubsection
1.1.2 Subsubsection
2. Section
2.1 Subsection
2.1.1 Subsubsection
2.1.2 Subsubsection
2.2 Subsection
2.2.1 Subsubsection
</code></pre>

<p>What am I doing wrong?</p>

<p>First, I use <code>lst</code> instead of <code>list</code>, because <code>list</code> is a function...</p>

<p>Next, for this to work you need to match first the longest<br>
series of numbers, then work down to the shortest one.</p>

<pre><code>toc = ''

for tocitem in lst:
    if re.match('(\d+)\.(\d+)\.(\d+)', tocitem):
        toc += '\t\t' + tocitem + '\n'
    elif re.match('(\d+)\.(\d+)', tocitem):
        toc += '\t' + tocitem + '\n'
    else:
        toc += tocitem + '\n'
</code></pre>

<p>And there's the output:</p>

<pre><code>
1. Section
        1.1 Subsection
                1.1.1 Subsubsection
                1.1.2 Subsubsection
2. Section
        2.1 Subsection
                2.1.1 Subsubsection
                2.1.2 Subsubsection
        2.2 Subsection
                2.2.1 Subsubsection
</code></pre>

<p>Now, this was regarding your question.<br>
However, I would do this without <code>if</code>s, more systematically<br>
as follows:</p>

<pre><code>toc = ''

for tocitem in lst:
    s = re.match(r'\S+', tocitem).group(0)
    digits = [x for x in s.split('.') if x.strip() != '']
    toc += (len(digits) - 1) * 4 * ' ' + tocitem + '\n'
</code></pre>

<p>The regex simply finds the first section up until the space,<br>
then splits on dot and take all the items which are not blank.<br></p>

python