0

考虑以下字典:

dic1 = {1:'string', '1': 'int'}

让我们应用字符串格式:

print("the value is {0[1]}".format(dic1))
result --> the value is string

但我怎样才能得到 ' the value is int' 结果呢?

4

2 回答 2

1

应该只是这个。

print("the value is {0}".format(dic1['1']))

唯一充当将{0}文本放入字符串的占位符。所以一个例子是。

>>> x=1
>>> y=2
>>> z=[3,4,5]
>>> print "X={0} Y={1} The last element in Z={2}".format(x,y,z[-1])
X=1 Y=2 The last element in Z=5

你也可以这样做来改变事情。数字引用了格式命令中要使用的参数。

>>> print "X={0} Y={1} The last element in Z={0}".format(x,y,z[-1])
X=1 Y=2 The last element in Z=1

现在看到我将字符串更改为Z={0}它实际上是x.format(x,y,z[-1])命令中使用。

于 2018-02-14T18:53:45.520 回答
1

有用,

print("the value is {0}".format(dic1['1']))

编辑以回答@Afshin 的评论

您可以在可迭代对象之前使用 * 运算符在函数调用中对其进行扩展。例如,

a = [1, 2, 3]
print("X={0} Y={1} The last element in Z={2}".format(*a))

或者

d = {'x': 1, 'y': 2, 'z': 3}
print("X={x} Y={y} The last element in Z={z}".format(**d))
于 2018-02-14T18:58:55.180 回答