extracting string.Template substitution placeholders
Steven D'Aprano
steve at pearwood.info
Mon Jan 13 02:24:30 EST 2014
On Sun, 12 Jan 2014 10:08:31 -0500, Eric S. Johansson wrote:
> As part of speech recognition accessibility tools that I'm building, I'm
> using string.Template. In order to construct on-the-fly grammar, I need
> to know all of the identifiers before the template is filled in. what is
> the best way to do this?
py> import string
py> t = string.Template("$sub some $text $here")
py> t.template
'$sub some $text $here'
Now just walk the template for $ signs. Watch out for $$ which escapes
the dollar sign. Here's a baby parser:
def get_next(text, start=0):
while True:
i = text.find("$", start)
if i == -1:
return
if text[i:i+2] == '$$':
start += i
continue
j = text.find(' ', i)
if j == -1:
j = len(text)
assert i < j
return (text[i:j], j)
start = 0
while start < len(t.template):
word, start = get_next(t.template, start)
print(word)
> can string.Template handle recursive expansion i.e. an identifier
> contains a template.
If you mean, recursive expand the template until there's nothing left to
substitute, then no, not directly. You would have to manually expand the
template yourself.
--
Steven
More information about the Python-list
mailing list