How to use str.format() with a dictionary in python?

前端 未结 3 1599
小鲜肉
小鲜肉 2021-02-05 07:56

What is wrong in this piece of code?

dic = { \'fruit\': \'apple\', \'place\':\'table\' }
test = \"I have one {fruit} on the {place}.\".format(dic)
print(test)

&         


        
3条回答
  •  南旧
    南旧 (楼主)
    2021-02-05 08:28

    You can use the following code too:

    dic = { 'fruit': 'apple', 'place':'table' }
    print "I have one %(fruit)s on the %(place)s." % dic
    

    If you want to know more about format method use: http://docs.python.org/library/string.html#formatspec

提交回复
热议问题