Python - How to format a variable number of arguments into a string?

We know that formatting one argument can be done with one %s in a line:

 >>> "Hello %s" % "world" 'Hello world' 

for two arguments, we can use two %s (duh!):

 >>> "Hello %s, %s" % ("John", "Joe") 'Hello John, Joe' 

So, how can I format a variable number of arguments without explicitly defining in the base line the number %s equal to the number of arguments to format? it would be great if something like this:

 >>> "Hello <cool_operator_here>" % ("John", "Joe", "Mary") Hello JohnJoeMary >>> "Hello <cool_operator_here>" % ("John", "Joe", "Mary", "Rick", "Sophie") Hello JohnJoeMaryRickSophie 

Is this possible, or the only thing I can do is to do something like:

 >>> my_args = ["John", "Joe", "Mary"] >>> my_str = "Hello " + ("".join(["%s"] * len(my_args))) >>> my_str % tuple(my_args) "Hello JohnJoeMary" 

NOTE. I need to do this using the string format operator %s .

UPDATE

It should be with %s , because a function from another library formats my string using this operator, given that I pass an unformatted string and arguments to format it, but it does some checks and corrections (if necessary) on the arguments before actually formatting .

So I need to call it:

 >>> function_in_library("Hello <cool_operator_here>", ["John", "Joe", "Mary"]) "Hello JohnJoeMary" 

Thank you for your help!

+8
python string string-formatting
source share
1 answer

You would use str.join() in the list without formatting the string, then interpolate the result:

 "Hello %s" % ', '.join(my_args) 

Demo:

 >>> my_args = ["foo", "bar", "baz"] >>> "Hello %s" % ', '.join(my_args) 'Hello foo, bar, baz' 

If some of your arguments are not yet strings, use a list comprehension:

 >>> my_args = ["foo", "bar", 42] >>> "Hello %s" % ', '.join([str(e) for e in my_args]) 'Hello foo, bar, 42' 

or use map(str, ...) :

 >>> "Hello %s" % ', '.join(map(str, my_args)) 'Hello foo, bar, 42' 

You would do the same with your function:

 function_in_library("Hello %s", ', '.join(my_args)) 

If you are constrained by a (rather arbitrary) constraint that you cannot use join in the list of interpolation arguments, use join to create a format string:

 function_in_library("Hello %s" % ', '.join(['%s'] * len(my_args)), my_args) 
+16
source share

All Articles