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!
python string string-formatting
Gerard
source share