带引号的字符串格式

String formatting with quotation marks

假设我有一个列表

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

我想创建以下字符串:

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

我尝试了以下方法:

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

但是输出是

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

我读过,但第二种方法似乎不再有效。

您有两个 {} 占位符,但只有一个变量。所以你需要让那些占位符知道他们需要使用同一个。此外,出于某种原因,您在第二个占位符中使用了双括号。这用于 "escape" 大括号,因此 {{}} 将变为 {}(而不用作实际的占位符)。

所以在解决了这两个问题之后:

>>> 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']

或用f-strings(对于Python >= 3.6):

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

为了更好地理解占位符的使用,请阅读 PyFormat, specifically the Basic Formatting part for info about positional place-holders, and the Named place-holders 部分 - 命名良好的占位符。

试试这个。你错过了一些东西。

list = ['a', 'b', 'c']
for i in list:
    print("foo_{} = bar[\'{}\']".format(i, i))