Is it possible to do partial string formatting with the advanced string formatting methods, similar to the string template safe_substitute()
function?
F
If you'd like to unpack a dictionary to pass arguments to format
, as in this related question, you could use the following method.
First assume the string s
is the same as in this question:
s = '{foo} {bar}'
and the values are given by the following dictionary:
replacements = {'foo': 'FOO'}
Clearly this won't work:
s.format(**replacements)
#---------------------------------------------------------------------------
#KeyError Traceback (most recent call last)
# in ()
#----> 1 s.format(**replacements)
#
#KeyError: 'bar'
However, you could first get a set of all of the named arguments from s and create a dictionary that maps the argument to itself wrapped in curly braces:
from string import Formatter
args = {x[1]:'{'+x[1]+'}' for x in Formatter().parse(s)}
print(args)
#{'foo': '{foo}', 'bar': '{bar}'}
Now use the args
dictionary to fill in the missing keys in replacements
. For python 3.5+, you can do this in a single expression:
new_s = s.format(**{**args, **replacements}}
print(new_s)
#'FOO {bar}'
For older versions of python, you could call update
:
args.update(replacements)
print(s.format(**args))
#'FOO {bar}'