Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
164 views
in Technique[技术] by (71.8m points)

string parsing - Python: splitting a function and arguments

Here are some simple function calls in python:

foo(arg1, arg2, arg3)
func1()

Assume it is a valid function call.

Suppose I read these lines while parsing a file.

What is the cleanest way to separate the function name and the args into a list with two elements, the first a string for the function name, and the second a string for the arguments?

Desired results:

["foo", "arg, arg2, arg3"]
["func1", ""]

I'm currently using string searches to find the first instance of "(" from the left side and the first instance of ")" from the right side and just splicing the string with those given indices, but I don't like how I am approaching the problem.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm currently doing something similar using regular expressions. Adapting my code to your case, the following works with the examples you provide.

import re

def explode(s):
    pattern = r'(w[wd_]*)((.*))$'
    match = re.match(pattern, s)
    if match:
        return list(match.groups())
    else:
        return []

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...