我有一个目录列表,我想创建一个缩进字符串
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']
期望的结果是:
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
我试过这个:
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'
但是标签不被识别,这就是我得到的
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
我做错什么了?你知道吗
颠倒
if re.match(...)
语句的顺序。您的所有项都通过了第一个测试,因此代码永远不会进入elif块。你知道吗试试这个:
第一个if条件也匹配其他情况。所以你必须改变顺序,或者采取更一般的方法:
相关问题 更多 >
编程相关推荐