i want to give multiple arguments to a functions from a string
for example if i have a function
def myfunc(x, y, z):
return x*y+z
How do i give it arguments from a string like '1, 2, 3', I want something like this
def myfunc(x, y, z):
return x*y+z
string = '1, 2, 3'
myfunc(string)
-
1if a string is the argument you want to be passing to the function make the conversion inside the function rather than outside.Ma0– Ma02017年03月14日 14:21:22 +00:00Commented Mar 14, 2017 at 14:21
4 Answers 4
'1, 2, 3' is a string representation of a tuple of ints. A simple way to handle that is to use ast.literal_eval which allows you to "safely evaluate an expression node or a string containing ... the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None":
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
The code can be written on one line like so:
myfunc(*ast.literal_eval(s))
For more information about how the asterisk in myfunc(*tup_of_int) works see Unpacking Argument Lists from The Python Tutorial.
Note: Do not be tempted to eval in place of ast.literal_eval. eval is really dangerous because it cannot safely handle untrusted input, so you should not get comfortable using it.
Comments
Replace the last line with myfunc(*map(int, string.split(','))).
string.split(',') splits the string into a list of the three arguments.
map(int, string.split(',')) converts the elements of the list to integers.
myfunc(*map(int, string.split(','))) splats the list so that the three elements of the list get passed as parameters.
This method relies on your input having the exact format as shown in your example string ('1,2,3' would not work). Steven's response is more robust so I recommend going with that one.
3 Comments
int will happily handle ' 2' (with a preceding space) so you can make your code more robust by splitting on a comma only instead of space+comma. This means that if the input becomes '1,2, 3' the code will still work.int could parse the spaces. I've updated my answer.Here is the code for your problem: First of all you have to split the string then proceed to next step:
def myfunc(x, y, z):
return x * y + z
a=raw_input()
x,y,z=map(int,a.split(","))
print myfunc(x,y,z)
Comments
One liner (although parsing string arguments like this could introduce vulnerabilities in your code).
>>> myfunc(*eval(string)) # myfunc((1, 2, 3))
5
2 Comments
eval when ast.literal_eval exists? It's like recommending someone use a handgun for a flyswatter. Even with a disclaimer it's a bad idea.