python 字典格式化字符串的问题

>>> "%(1)s" % {1:'a',2:'b'}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: '1'

下面这个就可以,为什么?

>>> "%(1)s" % {'1':'a','2':'b'}
'a'
阅读 3.8k
2 个回答

换成%d再试试看

KeyError应该类型错误。
我试过

"%(1)s" % {'3': 'a', '2': 'b'}

还是报原来的错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: '1'

看了这个%(1)s中的1是为了匹配key值的。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题