<p>正如@IgnacioVazquez Abrams所说,创建<a href="https://docs.python.org/3.6/library/string.html#string.Formatter" rel="noreferrer">^{<cd1>}</a>的子类,允许您扩展/更改格式字符串处理。</p>
<p>在您的情况下,必须重载方法<code>convert_field</code></p>
<pre><code>from string import Formatter
class ExtendedFormatter(Formatter):
"""An extended format string formatter
Formatter with extended conversion symbol
"""
def convert_field(self, value, conversion):
""" Extend conversion symbol
Following additional symbol has been added
* l: convert to string and low case
* u: convert to string and up case
default are:
* s: convert with str()
* r: convert with repr()
* a: convert with ascii()
"""
if conversion == "u":
return str(value).upper()
elif conversion == "l":
return str(value).lower()
# Do the default conversion or raise error if no matching conversion found
super(ExtendedFormatter, self).convert_field(value, conversion)
# return for None case
return value
# Test this code
myformatter = ExtendedFormatter()
template_str = "normal:{test}, upcase:{test!u}, lowcase:{test!l}"
output = myformatter.format(template_str, test="DiDaDoDu")
print(output)
</code></pre>