有没有更好的办法?使用字典格式化字符串

时间:2018-12-17 23:45:57

标签: python-3.x string dictionary formatting

是否有更好的方法来进行以下操作。

    template = """
This goes here {Item1},,, and here {Item2}
   and here {Item3}
"""

mydict = {'Item1':'Cat', 
          'Item2':'Dog', 
          'Item3':'Hamster', 
          'Item4':'Donkey'
         }

result = template.format(Item1=mydict['Item1'], Item2=mydict['Item2'], Item3=mydict['Item3'])

主要是格式字符串中的占位符的命名与字典中的键值完全相同。

但是,该词典包含的键值可能会超过占位符。占位符将始终是词典的子集

我尝试过

template.format(**mydict)

但是给出了KeyError异常。我曾希望默默地捕获该异常会起作用,但那不会

我的直觉是,除了上面的长期使用方法外,还必须有其他更Python化的方法来完成此操作。

谢谢

0 个答案:

没有答案