Reputation: 1412
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
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
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
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:
Upvotes: 2