search

Home  >  Q&A  >  body text

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'
PHP中文网PHP中文网2770 days ago774

reply all(2)I'll reply

  • 伊谢尔伦

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

    Change to %d and try again

    reply
    0
  • 阿神

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

    KeyError should be of typeError.
    I tried

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

    Still report the original error:

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

    I saw that the %(1)s in this 1 is to match the key value.

    reply
    0
  • Cancelreply