部分字符串格式化 [英] partial string formatting

查看:66
本文介绍了部分字符串格式化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用类似于字符串模板safe_substitute()函数的高级字符串格式化方法进行部分字符串格式化?

Is it possible to do partial string formatting with the advanced string formatting methods, similar to the string template safe_substitute() function?

例如:

s = '{foo} {bar}'
s.format(foo='FOO') #Problem: raises KeyError 'bar'

推荐答案

您可以通过覆盖映射将其转换为部分格式:

You can trick it into partial formatting by overwriting the mapping:

import string

class FormatDict(dict):
    def __missing__(self, key):
        return "{" + key + "}"

s = '{foo} {bar}'
formatter = string.Formatter()
mapping = FormatDict(foo='FOO')
print(formatter.vformat(s, (), mapping))

打印

FOO {bar}

当然,这个基本实现只适用于基本情况.

Of course this basic implementation only works correctly for basic cases.

这篇关于部分字符串格式化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆