Skip to main content
 首页 » 编程设计

python之拆分字符串,看起来像对参数的 Python 函数调用

2025年05月04日18wuhuacong

我正在尝试制作一个接受字符串的函数,该字符串看起来像 python 中的函数调用并将参数返回给函数 示例:

"fun(1, bar(x+17, 1), arr = 's,y')" 

结果:

["1", "bar(x+17, 1)", "arr = 's,y'"] 

使用正则表达式的问题是我不知道是否可以不在括号或引号内的逗号处分割。 谢谢。

编辑:这个Python: splitting a function and arguments没有正确回答问题,因为它没有处理括号或引号中的逗号。

正如@Kevin 所说,正则表达式无法解决这个问题,因为它们无法处理嵌套的括号。

请您参考如下方法:

你可以很简单地用类似的东西跟踪你自己的状态

def parse_arguments(s): 
    openers = "{[\"'(" 
    closers = "}]\"')" 
    state = [] 
    current = "" 
    for c in s: 
        if c == "," and not state: 
           yield current 
           current = "" 
        else: 
           current += c 
           if c in openers: 
              state.append(c) 
           elif c in closers: 
              assert state, "ERROR No Opener for %s"%c 
              assert state[-1] == openers[closers.index(c)],"ERROR Mismatched %s %s"%(state[-1],c) 
              state.pop(-1) 
    assert not state, "ERROR Unexpected End, expected %s"%state[-1] 
    yield current 
 
print list(parse_arguments("1, bar(x+17, 1), arr = 's,y'"))