Omar Alhussani
Omar Alhussani

Reputation: 342

Give multiple arguments to a function

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)

Upvotes: 1

Views: 142

Answers (4)

Rohit-Pandey
Rohit-Pandey

Reputation: 2159

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)

Upvotes: 0

FamousJameous
FamousJameous

Reputation: 1585

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.

Upvotes: 1

Steven Rumbalski
Steven Rumbalski

Reputation: 45542

'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.

Upvotes: 2

ospahiu
ospahiu

Reputation: 3525

One liner (although parsing string arguments like this could introduce vulnerabilities in your code).

>>> myfunc(*eval(string))  # myfunc((1, 2, 3))
5

Upvotes: -1

Related Questions