python - 为函数提供多个参数

标签 python string function arguments

我想从字符串中向函数提供多个参数
例如,如果我有一个函数

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_evalevalreally dangerous because it cannot safely handle untrusted input ,所以你不应该习惯使用它。

关于python - 为函数提供多个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42788389/

相关文章:

python - 如何使用 Flask/SQLAlchemy 将返回结果的数量限制为仅 1000 个最新条目?

c++ - 在 C++ 中如何检查字符串中的数据是否为数字?

python - python 2.7 中需要密码的 SSL 连接

javascript - ajax 返回空字符串而不是 json [python cgi]

php - 使用 PHP 代码替换 MYSQL 字符串

c++ - 对象数组,C++

r - 如何有效地部分应用 R 中的函数?

c - 函数原型(prototype) - 关闭参数检查

python 3 : How to best iterate over all lines in a big file (+1 million lines) in a random order

regex - 如何从字符串中获取第二个和第四个字符