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)
Answer from Martijn Pieters on Stack Overflow
Top answer
1 of 2
2

It's more Pythonic to use the str.format method rather than the old %s printf style from C. It's also more Pythonic to use the builtin modules:

>>> import datetime
>>> args1 = 2014, 10, 01
>>> args2 = 2014, 10, 01, 12
>>> args3 = 2014, 10, 01, 12, 25
>>> '{0}'.format(datetime.datetime(*args1))
'2014-10-01 00:00:00'
>>> '{0}'.format(datetime.datetime(*args2))
'2014-10-01 12:00:00'
>>> '{0}'.format(datetime.datetime(*args3))
'2014-10-01 12:25:00'

If you want a more generalized answer to

What is the most pythonic way to insert a variable number of arguments into a string?

Then you could define a function to do that, with positional arguments for the required arguments, and keyword arguments for the optional arguments:

def format_args(arg1, arg2, arg3, arg4=0, arg5=0, arg6=0):
    return '{0}, {1}, {2}, {3}, {4}, {5}'.format(
      arg1, arg2, arg3, arg4, arg5, arg6)

usage:

>>> format_args(*args1)
'2014, 10, 1, 0, 0, 0'
>>> format_args(*args2)
'2014, 10, 1, 12, 0, 0'
>>> format_args(*args3)
'2014, 10, 1, 12, 25, 0'
2 of 2
1

Agree that using datetime is preferable to home rolled solutions. To answer the more general question of interpolating variable arguments in format strings that have different numbers of arguments: the % operator requires a specific number of arguments, but string.format only requires the minimum number. Provide a function that will pad your starting arguments to the longest possible with defaults, then you can feed that to format.

from itertools import chain

date_only = [ 2014, 2, 29 ]
date_and_time = [ 2014, 10, 23, 4, 20, 0 ]
defaults = [ 0 ] * 6 # the most arguments your format string requires

date_strs = [ "{} {} {}", "{} {} {} {} {} {}" ]

for s in date_strs:
    print(s.format(*chain(date_only, defaults)))
    print(s.format(*chain(date_and_time, defaults)))

Output:

2014 2 29
2014 10 23
2014 2 29 0 0 0
2014 10 23 4 20 0
Top answer
1 of 2
2

Rather than hard coding your count, just count the number of valid braces in each template. A simplistic way of doing this is like this:

>>> "{} {} three {}".count("{}")
3
>>> "none".count("{}")
0

So your program would look something like this:

arguments = ["a", "b", "c", "d", "e", "f", "g"] 
templates = [
    "{{}} one",
    "none",
    "{} two {}",
    "{} {} three {}",
    "one2 {}",
    "and {{literal}} braces {{}}"
]

start = 0
for template in templates:
    count = template.count("{}")
    print(template.format(*arguments[start : start + count]))
    start += count

In the REPL:

>>> arguments = ["a", "b", "c", "d", "e", "f", "g"]
>>> templates = [
...     "{} one",
...     "none",
...     "{} two {}",
...     "{} {} three {}",
...     "one2 {}",
...     "and {{literal}} braces {{}}"
... ]
>>>
>>> start = 0
>>> for template in templates:
...     count = template.count("{}")
...     print(template.format(*arguments[start : start + count]))
...     start += count
...
{} one
none
b two c
d e three f
one2 g
and {literal} braces {}
2 of 2
1

You could join all your templates using a character that you're unlikely to see in the templates or arguments, do the string interpolation, and then split the result.

templates = [
    "{} one",
    "none",
    "{} two {}",
    "{} {} three {}",
    "one2 {}",
    "and {{literal}} braces {{}}"
]
arguments = ["a", "b", "c", "d", "e", "f", "g"] 

joined_template = chr(1).join(templates)

formatted_string = joined_template.format(*arguments)

formatted_templates = formatted_string.split(chr(1))

formatted_templates is now:

['a one',
 'none',
 'b two c',
 'd e three f',
 'one2 g',
 'and {literal} braces {}']
🌐
Python
docs.python.org › 3 › library › string.html
Common string operations — Python 3.14.7 documentation
The built-in string class provides ... complex variable substitutions and value formatting via the format() method described in PEP 3101. The Formatter class in the string module allows you to create and customize your own string formatting behaviors using the same implementation as the built-in format() method. ... The primary API method. It takes a format string and an arbitrary set of positional and keyword arguments...
🌐
UC Berkeley Statistics
stat.berkeley.edu › ~spector › extension › python › notes › node67.html
Variable Number of Arguments
If we call the function with a collection of strings as arguments, it will check them all, and return the maximum length of any of them: >>> longlen('apple','banana','cantaloupe','cherry') 10 · A similar technique can be used to create functions which can deal with an unlimited number of keyword/argument pairs. If an argument to a function is preceded by two asterisks, then inside the function, Python will collect all keyword/argument pairs which were not explicitly declared as arguments into a dictionary.
Top answer
1 of 4
1

I was under the impression that you also wanted to to be able to randomly add new items to the lists for each key. I was bored so I said why not and wrote the following code up. It will find the longest length of each entry of each key-value and put it in d_max, doesn't matter what type it is, as long as it can be converted to a string and also supports randomly adding things to the values (see last two lines of d). I tried to comment it well, but ask something if you need to.

d = {1: ['Spices', 39],
     2: ['Cannons', 43],
     3: ['Tea', 31],
     4: ['Contraband', 46],
     5: ['Fruit', 38],
     6: ['Textiles', 44],
     7: ['Odds and Ends', 100, 9999],
     8: ['Candies', 9999, 'It\'s CANDY!']} 
d_max = []

# Iterate over keys of d
for k in d:
    # Length of the key
    if len(d_max) <= 0:
        d_max.append(len(str(k)) + 1)
    elif len(str(k))+ 1 > d_max[0]:
        d_max[0] = len(str(k)) + 1 

    # Iterate over the length of the value
    for i in range(len(d[k])):
        # If the index isn't in d_max then this must be the longest
        # Add one to index because index 0 is the key's length
        if len(d_max) <= i+1:
            d_max.append(len(str(d[k][i])))
            continue
        # This is longer than the current one
        elif len(str(d[k][i])) + 1 > d_max[i+1]:
            d_max[i+1] = len(str(d[k][i])) + 1

for k,v in d.items():
    list_var = [k] + v

    # A list of values to unpack into the string
    vals = []
    # Add the value then the length of the space
    for i in range(len(list_var)):
        vals.append(list_var[i])
        vals.append(d_max[i])

    print(("{:<{}} " * len(list_var)).format(*vals))

Output:

1  Spices         39    
2  Cannons        43    
3  Tea            31    
4  Contraband     46    
5  Fruit          38    
6  Textiles       44    
7  Odds and Ends  100   9999         
8  Candies        9999  It's CANDY! 

If you wanted it all in one line then I'm afraid I can't help you :( There's also probably a cleaner way to do the second loop but that's all I could think up on a few hours of sleep.

2 of 4
0

do you mean you want to do something like:

list_var = [k] + v[:2]

This will work if the values list has too many items (It'll just remove the excess).

🌐
Educative
educative.io › home › courses › clean code in python › variable number of arguments in python
Using Variable Number of Arguments in Python Functions
Python, as well as other languages, has built-in functions and constructions that can take a variable number of arguments. Consider, for example, string interpolation functions (whether it be by using the % operator or the format method for strings), which follow a similar structure to the printf function in C, a first positional parameter with the string format, followed by any number of arguments that will be placed on the markers of that formatting string.
Find elsewhere
🌐
Python
peps.python.org › pep-3101
PEP 3101 – Advanced String Formatting | peps.python.org
The built-in string class (and also the unicode class in 2.6) will gain a new method, ‘format’, which takes an arbitrary number of positional and keyword arguments:
🌐
Codecademy Forums
discuss.codecademy.com › frequently asked questions › python faq
How do I insert multiple variables with string formatting? - Python FAQ - Codecademy Forums
June 18, 2018 - Question How do I insert multiple variables with string formatting? Answer So long as your number of %s placeholders matches the number of variables you are providing after the %, it will insert them in the order in which you provide them. Take a look over the code below for a better understanding: var1 = “awesome” var2 = “ever” print “Codecademy has the most %s coding lessons %s!” % (var1, var2) # displays: “Codecademy has the most awesome coding lessons ever!” If you don’t have the same num...
🌐
PyFormat
pyformat.info
PyFormat: Using % and .format() for great good!
Use it if the order of your arguments is not likely to change and you only have very few elements you want to concatenate. Since the elements are not represented by something as descriptive as a name this simple style should only be used to format a relatively small number of elements. ... With new style formatting it is possible (and in Python ...
🌐
Real Python
realpython.com › python-formatted-output
A Guide to Modern Python String Formatting Tools – Real Python
February 1, 2025 - By the end of this tutorial, you’ll understand that: String interpolation in Python involves embedding variables and expressions into strings. You create an f-string in Python by prepending a string literal with an f or F and using curly braces to include variables or expressions. You can use variables in Python’s .format() method by placing them inside curly braces and passing them as arguments...
🌐
Delft Stack
delftstack.com › home › howto › python › how to print multiple arguments in python
How to Print Multiple Arguments in Python | Delft Stack
March 11, 2025 - In this code, the f before the string indicates that it’s an f-string. You can directly embed the variables within curly braces {}. This method not only improves readability but also makes it easier to format your output.
🌐
Telerik
telerik.com › blogs › string-formatting-python
String Formatting in Python
January 6, 2023 - The formatted string literals which was introduced in Python 3 is the latest and most straightforward way of formatting strings in Python. We put the letter f or F in front of a string literal and specify expressions within curly braces {} in the string. Expressions within formatted literals can directly access variables in the namespace. Which means we don’t need to pass in any arguments or worry about matching placeholders with arguments anymore.
Top answer
1 of 4
58

You can use the str.format() method, which lets you interpolate other variables for things like the width:

'Number {i}: {num:{field_size}.2f}'.format(i=i, num=num, field_size=field_size)

Each {} is a placeholder, filling in named values from the keyword arguments (you can use numbered positional arguments too). The part after the optional : gives the format (the second argument to the format() function, basically), and you can use more {} placeholders there to fill in parameters.

Using numbered positions would look like this:

'Number {0}: {1:{2}.2f}'.format(i, num, field_size)

but you could also mix the two or pick different names:

'Number {0}: {1:{width}.2f}'.format(i, num, width=field_size)

If you omit the numbers and names, the fields are automatically numbered, so the following is equivalent to the preceding format:

'Number {}: {:{width}.2f}'.format(i, num, width=field_size)

Note that the whole string is a template, so things like the Number string and the colon are part of the template here.

You need to take into account that the field size includes the decimal point, however; you may need to adjust your size to add those 3 extra characters.

Demo:

>>> i = 3
>>> num = 25
>>> field_size = 7
>>> 'Number {i}: {num:{field_size}.2f}'.format(i=i, num=num, field_size=field_size)
'Number 3:   25.00'

Last but not least, of Python 3.6 and up, you can put the variables directly into the string literal by using a formatted string literal:

f'Number {i}: {num:{field_size}.2f}'

The advantage of using a regular string template and str.format() is that you can swap out the template, the advantage of f-strings is that makes for very readable and compact string formatting inline in the string value syntax itself.

2 of 4
8

I prefer this (new 3.6) style:

name = 'Eugene'
f'Hello, {name}!'

or a multi-line string:

f'''
Hello,
{name}!!!
{a_number_to_format:.1f}
'''

which is really handy.

I find the old style formatting sometimes hard to read. Even concatenation could be more readable. See an example:

'{} {} {} {} which one is which??? {} {} {}'.format('1', '2', '3', '4', '5', '6', '7')
🌐
Guru99
guru99.com › home › python › python string format() explain with examples
Python String format() Explain with EXAMPLES
July 10, 2026 - It will return the final string, with valid values replaced in place of the placeholders given in curly brackets. The placeholders in the template string are represented using curly brackets, e.g. {}. The placeholder can be empty {}, or it can have a variable for e.g {name} , or it can have a number index e.g {0} , {1} etc. The Python String format() method will scan the original strings for placeholders. The placeholders can be empty curly brackets ({}), positional arguments i.e the string can have placeholders with index 0, 1 for e.g {0}, {1} etc.
🌐
Linux Hint
linuxhint.com › python_string_formatting
Python String Formatting – Linux Hint
#!/usr/bin/env python3 # Initialize two string variables employee = "John" profession = "Programmer" # Print the formatted values of the variables print("%s is a %s" % (employee,profession)) ... The output is shown on the right side of the image. This method can take both positional and keyword parameters as arguments.