我想从字符串中向函数提供多个参数
例如,如果我有一个函数
def myfunc(x, y, z):
return x*y+z
我如何从像“1,2,3”这样的字符串中给它参数, 我想要这样的东西
def myfunc(x, y, z):
return x*y+z
string = '1, 2, 3'
myfunc(string)
最佳答案
'1, 2, 3'
是整数元组的字符串表示形式。处理这个问题的一个简单方法是使用 ast.literal_eval
它允许您“安全地评估”表达式节点或包含以下 Python 文字结构的字符串:字符串、字节、数字、元组、列表、字典、集合、 bool 值和 无
”:
import ast
s = '1, 2, 3'
tup_of_int = ast.literal_eval(s) # converts '1, 2, 3' to (1, 2, 3)
myfunc(*tup_of_int) # unpack items from tup_of_int to individual function args
代码可以写成一行,如下所示:
myfunc(*ast.literal_eval(s))
有关 myfunc(*tup_of_int)
中星号如何工作的更多信息,请参阅 Unpacking Argument Lists来自The Python Tutorial .
注意:不要试图用eval
来代替ast.literal_eval
。 eval
是 really dangerous because it cannot safely handle untrusted input ,所以你不应该习惯使用它。
关于python - 为函数提供多个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42788389/