Python 3 - 关于格式化输出的简单事情

时间:2015-03-29 06:47:48

标签: python-3.x

以下代码返回不同级别的标记:

import re

def matches(line, opendelim='(', closedelim=')'):
stack = []

for m in re.finditer(r'[{}{}]'.format(opendelim, closedelim), line):
    pos = m.start()

    if line[pos-1] == '\\':
        continue

    c = line[pos]

    if c == opendelim:
        stack.append(pos+1)

    elif c == closedelim:
        if len(stack) > 0:
            prevpos = stack.pop()
            yield (line[prevpos:pos], len(stack))
        else:
            print("encountered extraneous closing quote at pos {}: '{}'".format(pos, line[pos:] ))
            pass

if len(stack) > 0:
    for pos in stack:
        print("expecting closing quote to match open quote starting at: '{}'"
              .format(line[pos-1:]))

line = 'f_0(a,f_1(b,f_2(f_3(f_4(a)),f_3(h)),f_2(f_3(a))),f_1(f_2(f_3(a))))'
for part, level in matches(line):
    if level == 2:
        print(part)

给我以下输出:

f_3(f_4(a)),f_3(h)
f_3(a)
f_3(a)

有没有办法可以用下面的表格格式化我的输出? :

['f_3(f_4(a))', 'f_3(h)', 'f_3(a)', 'f_3(a)']

我是python的新手。我可以请一些帮助。

1 个答案:

答案 0 :(得分:0)

您可以使用列表推导并一次打印所有结果:

print [part for part, level in matches(line) if level == 2]

您也可以加入您的结果:

print ','.join([part for part, level in matches(line) if level == 2])