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