
您可以遵循PEP 3101中的建议,并使用子类Formatter:
import stringclass BlankFormatter(string.Formatter): def __init__(self, default=''): self.default=default def get_value(self, key, args, kwds): if isinstance(key, str): return kwds.get(key, self.default) else: return string.Formatter.get_value(key, args, kwds)kwargs = {"name": "mark", "adj": "mad"} fmt=BlankFormatter()print fmt.format("My name is {name} and I'm really {adj}.", **kwargs)# My name is mark and I'm really mad.print fmt.format("My name is {name} and I'm really {adjective}.", **kwargs)# My name is mark and I'm really .从Python
3.2开始,您可以使用.format_map作为替代:
class Default(dict): def __missing__(self, key): return '{'+key+'}'kwargs = {"name": "mark"}print("My name is {name} and I'm really {adjective}.".format_map(Default(kwargs)))打印:
My name is mark and I'm really {adjective}.欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)