将我的函数的输出定向到另一个函数

2024-04-26 05:38:00 发布

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

我的代码:

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(g_1(a, g_2(a, b, g_3(c)), g_2(g_3(a, b, g_4(a), e))))"
a = str(print(','.join([part for part, level in matches(line) if level == 1])))
print(extract_tokens(a))

当我分别运行这两个函数时它会返回。在单个脚本文件中运行时,如何获取输出?你知道吗


Tags: inposreformatforlenifstack
1条回答
网友
1楼 · 发布于 2024-04-26 05:38:00

请注意,print始终return None,因此此行:

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

相当于:

print(...)
a = str(None)

因此,当您运行时:

print(extract_tokens(a))

['None']作为输出。问题不是调用函数,而是传递的参数。把print(a)放在另一行,你就没事了。你知道吗

相关问题 更多 >