遗憾的是内置格式化程序不允许这样做。一个明显的语法扩展是允许在必要时引用键。您的格式字符串将是这样的:
format('{"with:colon"} and {hello}'
幸运的是,扩展 Formatter 以提供这种语法似乎很容易,这是一个 POC 实现:
class QuotableFormatter(string.Formatter):
def __init__(self):
self.super = super(QuotableFormatter, self)
self.super.__init__()
self.quotes = {}
def parse(self, format_string):
fs = ''
for p in re.findall(r'(?:".+?")|(?:[^"]+)', format_string):
if p[0] == '"':
key = '_q_' + str(len(self.quotes))
self.quotes[key] = p[1:-1]
fs += key
else:
fs += p
return self.super.parse(fs)
def get_field(self, field_name, args, kwargs):
if field_name.startswith('_q_'):
field_name = self.quotes[field_name]
return self.super.get_field(field_name, args, kwargs)
用法:
d = {'hello': 'world', 'with:colon': 'moo', "weird!r:~^20": 'hi'}
print QuotableFormatter().format('{"with:colon":*>20} and {hello} and {"weird!r:~^20"}', **d)
# *****************moo and world and hi