打印字典中的元素时,print命令中的0索引是什么



我试过这段代码,但我不明白为什么我们在{0[a]}中使用0索引。

Day={'a':'Saturday','b':'Sunday','c':'Monday',
'd':'Tuesday','e':'Wednesday','f':'Thursday','g':'Friday'}
print('the first days is {0[a]} , second days is {0[b]}'.format(Day))

0指传递给format(...)函数的第一个参数。1是第二个,依此类推

或者,您可以将名称参数传递给format,并在字符串中使用它们的名称。

0指的是str.format方法的第一个参数
因此,您的打印相当于

print('the first days is {0} , second days is {1}'.format(Day['a'], Day['b']))

print(f"the first days is {Day['a']} , second days is {Day['b']}")

0不是用来索引字典的,它是用来获取.format(..)括号中的第一项。

示例:

>>> '{0} {1}'.format('Hello', 'World')
'Hello World'
>>> 

最新更新