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

前端 未结 3 1504
小鲜肉
小鲜肉 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:23

    There is ''.format_map() function since Python 3.2:

    test = "I have one {fruit} on the {place}.".format_map(dic)
    

    The advantage is that it accepts any mapping e.g., a class with __getitem__ method that generates values dynamically or collections.defaultdict that allows you to use non-existent keys.

    It can be emulated on older versions:

    from string import Formatter
    
    test = Formatter().vformat("I have one {fruit} on the {place}.", (), dic)
    

提交回复
热议问题