<h2>在python中使用自定义占位符标记<code>string.format()</code></h2>
<h2>上下文</h2>
<ul>
<li>Python2.7</li>
<li><code>string.format()</code></li>
<li>允许自定义占位符语法的替代方法</li>
</ul>
<h2>问题</h2>
<p>我们希望在python str.format()中使用自定义占位符分隔符</p>
<ul>
<li><code>string.format()</code>功能强大,但不支持对占位符分隔符的修改。</li>
<li><code>string.format()</code>使用大括号,这很常见,并导致<a href="https://en.wikipedia.org/wiki/Delimiter#Delimiter_collision" rel="nofollow noreferrer">Delimiter collision</a></li>
<li><code>string.format()</code>默认的解决方法是将分隔符加倍,这可能很麻烦。</li>
</ul>
<h2>解决方案</h2>
<p>我们编写了一个扩展本地python的自定义类<code>str.format()</code></p>
<ul>
<li>使用自定义类扩展本机python <code>string.Formatter</code></li>
<li>配置<code>string.format()</code>以支持任意分隔符占位符语法</li>
<li>允许其他增强功能,如自定义格式化程序和筛选器</li>
</ul>
<h2>示例001:自定义<code>ReFormat</code>类的演示使用</h2>
<ul>
<li>我们编写了一个自定义的<code>ReFormat</code>类,它扩展了python <code>str.format()</code></li>
</ul>
<pre class="lang-python prettyprint-override"><code># import custom class
import ReFormat
# prepare source data
odata = { "fname" : "Planet",
"lname" : "Earth",
"age" : "4b years",
}
# format output using .render()
# method of custom ReFormat class
#
vout = ReFormat.String("Hello &lt;%fname%&gt; &lt;%lname%&gt;!",odata).render()
print(vout)
</code></pre>
<h2>陷阱</h2>
<ul>
<li>需要扩展类<code>str.format()</code></li>
<li>不打算作为完全兼容沙盒的模板解决方案的替代品</li>
</ul>