Search code examples
pythonstring-formatting

How to substitute variables into Python format string


I have a Python string like such:

template = '{a} or {b} but not {c}; {d} and {e}, not {f}'

Later, variables a, b, c, d, e, and f are defined. They are not defined before template is, so I cannot use an f-string literal. I want to substitute their values into template.

This could be achieved by using the .format() string method:

template.format(a=a, b=b, c=c, d=d, e=e, f=f)

However, I am looking for a more compact way of expressing this.

Using **kwargs with globals() works if the variables are global:

template.format(**globals())

However, I am looking for something that works for locals or globals — something concise, which effectively produces the same result as using an f-string literal like:

template = f'{a} or {b} but not {c}; {d} and {e}, not {f}'

Again, an f-string does not work in this case because the letter variables are not defined yet when template is defined.

Thank you!


Solution

  • You can use locals(). At the module level, locals() and globals() are the same dictionary.

    Update : If some variables are in global and some of them are in local you can Union them using new | operator:

    template = '{a} or {b} but not {c}; {d} and {e}, not {f}'
    
    a = 10;b = 20;c = 30;d = 40
    
    def fn():
        e = 50;f = 60;h = 70
        print(template.format(**globals() | locals()))
        
    fn()
    

    or

    def fn():
        print(template.format(**{**globals(), **locals()}))
    

    The local dictionary will override values in global dictionary.