Search code examples
pythonstring-formatting

String formatting with quotation marks


Say I have a list

list = ['a', 'b', 'c']

And I want to create the following strings:

foo_a = bar['a']
foo_b = bar['b']
foo_c = bar['c']

I tried the following:

for i in list:
    print("foo_{} = bar['{{}}']".format(i))

But the output is

foo_a = bar['{}']
foo_b = bar['{}']
foo_c = bar['{}']

I have read Why is this usage of python F-string interpolation wrapping with quotes? but the second method does not seem to work anymore.


Solution

  • You have two {} place-holders but only one variable. So you need to let those place-holders know they need to use the same one. Also, for some reason you use double-braces in the second place-holder. This is used to "escape" the braces, so {{}} will become {} (and not serve as an actual place-holder).

    So after fixing these two issues:

    >>> list = ['a', 'b', 'c']
    >>> for i in list:
            print("foo_{i} = bar['{i}']".format(i=i))
         #  print("foo_{0} = bar['{0}']".format(i))
    
    foo_a = bar['a']
    foo_b = bar['b']
    foo_c = bar['c']
    

    Or with f-strings (for Python >= 3.6):

    for i in list:
        print(f"foo_{i} = bar['{i}']")
    

    To better understand the use of place holders, read more at PyFormat, specifically the Basic Formatting part for info about positional place-holders, and the Named place-holders part for - well - named place-holders.