Python 3's str.format()
function inserts its arguments into
replacement fields delimited by braces {}
in the string str
. The
arguments of format()
can include tuple- or keyword-arguments whose
length may be uncertain before runtime, and they will be unpacked when
format()
is actually called.
However, even if the arguments are of uncertain number, it seems to me
that the bracket-delimited replacement fields in str
are normally not.
Only if the string is constructed by concatenation in response to the
number of arguments of format
is it possible for each of those
arguments to be assured a corresponding replacement field:
In [1]: user_input = input('What did R. Crumb say? ')
Out[1]: What did R. Crumb say? Are the lumpen proletariat a lost cause?
In [2]: variable_length_args = user_input.split()
In [3]: the_string = [str(i) for i in range(len(variable_length_args))]
In [4]: the_string = '"{' + '}" and "{'.join(the_string) + '}"'
In [5]: the_string.format(\*variable_length_args)
Out[5]: '"Are" and "the" and "lumpen" and "proletariat" and "a" and "lost" and "cause?"'
Or is there some other special syntax for ensuring the right number of replacement fields, if that number is not known until runtime?
[end]