登录

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'
# Python
PHP中文网PHP中文网2147 天前393 次浏览

全部回复(2) 我要回复

  • 伊谢尔伦

    伊谢尔伦2017-04-17 15:37:57

    换成%d再试试看

    回复
    0
  • 阿神

    阿神2017-04-17 15:37:57

    KeyError应该类型错误。
    我试过

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

    还是报原来的错误:

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

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

    回复
    0
  • 取消回复发送