Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

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

We know that formatting one argument can be done using one %s in a string:

>>> "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 having to explicitly define within the base string a number of %s equal to the number of arguments to format? it would be very cool if something like this exists:

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

Is this even possible or the only thing I could do about it 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 it with the %s string formatting operator.

UPDATE:

It needs to be with the %s because a function from another library formats my string using that operator given that I pass the unformatted string and the args to format it, but it makes some checking and corrections (if needed) on the args before actually making the formatting.

So I need to call it:

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

Thanks for your help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You'd use str.join() on the list without string formatting, 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'd do the same with your function:

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

If you are limited by a (rather arbitrary) restriction that you cannot use a join in the interpolation argument list, use a join to create the formatting string instead:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...