radpotato
radpotato

Reputation: 1412

List items in a template string

I'm sure I must be missing something, is there a way of listing all the templates in an instance of string.Template? Or do I really have to revert to regex to find them?

Upvotes: 0

Views: 1641

Answers (3)

Kris Taylor
Kris Taylor

Reputation: 1

This would use a regex, but would this work as well?

s = Template('$who likes $what $$ $another')
split_re = r'([$][a-z]+)'
[word[1:] for word in re.findall(split_re, s)]

['who', 'what', 'another']

This would extract any placeholder words from a string, excluding any double $'s.

Upvotes: 0

Duncan
Duncan

Reputation: 95742

Here's a completely different way to do it (triggered by Lutz Horn's answer but a lot simpler):

from string import Template
from collections import defaultdict

d = defaultdict(str)
s = Template('$who likes $what $$ ${another}')
s.substitute(d)
print(d.keys())

Gives the expected output.

Upvotes: 0

Duncan
Duncan

Reputation: 95742

You can use the regex that the template uses and extract the names:

>>> s = Template('$who likes $what $$ ${another}')
>>> [m.group('named') or m.group('braced')
    for m in s.pattern.finditer(s.template)
    if m.group('named') or m.group('braced')]
['who', 'what', 'another']

The documentation says the regex has 4 capturing groups:

  • escaped – This group matches the escape sequence, e.g. $$, in the default pattern.
  • named – This group matches the unbraced placeholder name; it should not include the delimiter in capturing group.
  • braced – This group matches the brace enclosed placeholder name; it should not include either the delimiter or braces in the capturing group.
  • invalid – This group matches any other delimiter pattern (usually a single delimiter), and it should appear last in the regular expression.

Upvotes: 2

Related Questions