我试过这段代码,但我不明白为什么我们在{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'
>>>