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

前端 未结 1 1982
旧巷少年郎
旧巷少年郎 2020-12-17 10:03

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

>>> \"Hello %s\" % \"world         


        
相关标签:
1条回答
  • 2020-12-17 10:28

    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)
    
    0 讨论(0)
提交回复
热议问题