如果未以str.format传递,则将值保留为空白 [英] Leaving values blank if not passed in str.format
问题描述
我遇到了一个非常简单的问题,我无法提出一个优雅的解决方案.
I've run into a fairly simple issue that I can't come up with an elegant solution for.
我正在使用str.format
在一个函数中创建一个字符串,该函数以dict
替代形式传递以用于格式.我想创建字符串并将其值格式化(如果已传递),否则将其留空.
I'm creating a string using str.format
in a function that is passed in a dict
of substitutions to use for the format. I want to create the string and format it with the values if they're passed and leave them blank otherwise.
Ex
kwargs = {"name": "mark"}
"My name is {name} and I'm really {adjective}.".format(**kwargs)
应该返回
"My name is mark and I'm really ."
而不是抛出KeyError
(如果我们什么都不做,将会发生什么情况).
instead of throwing a KeyError
(Which is what would happen if we don't do anything).
令人尴尬的是,对于这个问题,我什至无法提出一个优雅的解决方案.我想我可以通过不使用str.format
来解决此问题,但我宁愿使用内置的(主要是我想要的功能).
Embarrassingly, I can't even come up with an inelegant solution for this problem. I guess I could solve this by just not using str.format
, but I'd rather use the built-in (which mostly does what I want) if possible.
注意:我事先不知道将使用什么键.如果有人包含密钥但没有将其放入kwargs字典中,我将尝试以失败告终.如果我以100%的准确度知道将查找哪些键,则只需填充所有键并完成操作即可.
Note: I don't know in advance what keys will be used. I'm trying to fail gracefully if someone includes a key but doesn't put it in the kwargs dict. If I knew with 100% accuracy what keys would be looked up, I'd just populate all of them and be done with it.
推荐答案
You can follow the recommendation in PEP 3101 and use a subclass Formatter:
import string
class 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 作为替代:
As of Python 3.2, you can use .format_map as an alternative:
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}.
这篇关于如果未以str.format传递,则将值保留为空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!