dingo_d dingo_d - 3 months ago 10
Python Question

Python create indented string from a list

I have a list of table of contents that I'd like to create into an indented string

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']


And the desired result is this:

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


I've tried this:

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'


But the tabs are not recognized, that is I get this

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


What am I doing wrong?

Answer

Reverse the order of if re.match(...) statements. All of your items pass the first test so the code never enters elif block.

Comments