擅长:python、mysql、java
<p>这就是格式化程序类的子类的用途。请尝试以下操作:</p>
<pre><code>import string
class NegativeParenFormatter(string.Formatter):
def format_field(self, value, format_spec):
try:
if value<0:
return "(" + string.Formatter.format_field(self, -value, format_spec) + ")"
else:
return string.Formatter.format_field(self, value, format_spec)
except:
return string.Formatter.format_field(self, value, format_spec)
f = NegativeParenFormatter()
print f.format("{0} is positive, {1} is negative, {2} is a string", 3, -2, "-4")
</code></pre>
<p>这张照片:</p>
<pre><code>'3 is positive, (2) is negative, -4 is a string'
</code></pre>