KeyError-format

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dqchouyang/article/details/79952329

看问题:

>>> "{'ip':{0}, 'nat':{1}}".format("33", "44")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: "'ip'"

what? 发生了什么?用了多年的format(无视参数的类型),怎么就报错了

>>> "{'ip':%s, 'nat':%s}" % ("33", "44")
"{'ip':33, 'nat':44}"
>>>

这个没有报错是对的,那么继续往下看

>>> "{ip}{nat}".format("33", "44")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'ip'
>>> 
>>> 
>>> "{ip}{nat}".format(ip="33", nat="44")
'3344'
>>> 
>>> "{'ip'}{'nat'}".format(ip="33", nat="44")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: "'ip'"
>>> 

看到区别了把,"{'ip':{0}, 'nat':{1}}".format("33", "44") 中的format是要识别’{‘的,它会认为'ip' 整体是一个需要被替换的变量,而format("33", "44") 中并没有对应的变量名来替换,所以就报了KeyError错误。

猜你喜欢

转载自blog.csdn.net/dqchouyang/article/details/79952329
今日推荐