我正在尝试编写一个辅助函数来帮助我生成带有函数定义的新文件。以下是部分代码:
def new_function_file(file_name, fun_name, arguments):
f = open(file_name + ".py", 'w')
f.write("\tdef " + fun_name + str(("self", ) + arguments) + ":\n")
new_leetcode_file("testfile", "test", ("arr1", "arr2"))
但是,这会在 testfile.py 中生成“def test('self', 'arr1', 'arr2'):”。我想知道如何在不生成单引号的情况下正确解析参数?
最佳答案
格式化打印在这里可能很有用,同时还可以稍微分解一下:
def new_function_file(file_name, fun_name, arguments):
f = open(file_name + ".py", 'w')
# expand the arguments and join with "," separators:
args = ", ".join(arguments)
# use formatted print to put it all together nicely:
write_string = "\tdef {fn}(self, {ar}):\n".format(fn=fun_name, ar=args)
f.write(write_string)
对于您的演示输入:
new_leetcode_file("testfile", "test", ("arr1", "arr2"))
“writestring”将是:
'\tdef test(self, arr1, arr2):\n'
您可以将其直接写入文件,无需任何其他标点符号。
关于python - 动态创建函数文件中的函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31908302/