Python从lis创建缩进字符串

2024-10-01 05:00:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个目录列表,我想创建一个缩进字符串

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

我做错什么了?你知道吗


Tags: 字符串inre目录列表forifmatch
3条回答

颠倒if re.match(...)语句的顺序。您的所有项都通过了第一个测试,因此代码永远不会进入elif块。你知道吗

试试这个:

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

第一个if条件也匹配其他情况。所以你必须改变顺序,或者采取更一般的方法:

toc = ''
for tocitem in list:
    number = tocitem.split()[0]
    toc += '\t' * number.strip('.').count('.') + tocitem + '\n'

相关问题 更多 >