I have a format string that I am creating dynamically based on user input. I am collecting the arguments for the format string in a list, and I'd like to know how to unpack them at the end of the format string. I've seen some questions that seem related to this, but I'm very new to Python and I can't seem to apply their solutions to my case.
The idea of what I'd like to do is:
my_string = "string contents" % tuple([for item in var_array])
Of course this isn't valid syntax but hopefully it describes what I am trying to do: I'd like to unpack var_array as my list of arguments without knowing the length of var_array ahead of time. How could I do this?
Edit: I'll attempt to better explain my problem. I'm creating a format string by concatenating an unknown number of format strings. Thus my final string will have a a variable number of %s and therefore a variable number of args that are collected in a list.
For example:
"My format string might have %s or %s arguments" %([arg_list]) //here arg_list has 2 arguments
"But my format string might also have %s or %s or %s arguments. %([arg_list]) //here arg_list has 3 arguments
The length of the format string, and the number of arguments are variable based on user input so I want to be able to tack on a list of args at the end of the final string. Is this possible?
Here is an approach that goes from arguments to a formatted string (error checking is still needed):
>>> def StartDance(*args):
return "%d, %d, %d, %d!" % tuple(args)
>>> StartDance(5, 6, 7, 8)
'5, 6, 7, 8!'
Here is a more robust solution to error checking but I'm presenting it as a separate answer considering how much extra complexity it is adding:
>>> def StartDance(*args):
return (", ".join(["%d"] * len(args))+"!") % tuple(args)
>>> StartDance(5, 6, 7, 8)
'5, 6, 7, 8!'
>>> StartDance(5, 6, 7, 8, 9, 10)
'5, 6, 7, 8, 9, 10!'
>>> StartDance(1)
'1!'
And here is a function returning a list which is being unpacked as arguments only to have these arguments treated as a list (Python is fun :)
>>> StartDance(*range(5,9))
'5, 6, 7, 8!'
Assuming what you want to make into a string supports the str
builtin, you can do:
def join_args(*args):
return " ".join([str(x) for x in args])
print(join_args(1,2,3,4,5,6))
print(join_args('1','2','3','4'))
Out:
1 2 3 4 5 6
1 2 3 4
You could also use the following for a more flexible string:
def join_args(fmstr, *args):
return fmstr.format(*args)
print(join_args("One: {} Two: {} Three: {} Four: {}", 1,2,3,4))
Out:
One: 1 Two: 2 Three: 3 Four: 4
Just make sure there are an equal number of args and {}
.
You're very close, try something like this:
"%s my %s is %s" % tuple(["Hi", "name", "butch"])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With