我想写一个带字符串和字典的方法.该方法应扫描字符串并将{word}内的每个单词替换为dic ["word"]的值.
例:
s = "Hello my name is {name} and I like {thing}" dic = {"name": "Mike", "thing": "Plains"} def rep(s, dic): return "Hello my name is Mike and I like Plains"
我的意思是它是一个简单的问题,易于解决,但我搜索了很好的python方式.
您可以dict
在str.format
函数内解压缩为:
>>> s = "Hello my name is {name} and I like {thing}" >>> dic = {"name": "Mike", "thing": "Plains"} # v unpack the `dic` dict >>> s.format(**dic) 'Hello my name is Mike and I like Plains'
要了解如何在Python中解压缩,请检查:**(双星)和*(星)对参数的作用是什么?