'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?
Solution 1:[1]
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.
Solution 2:[2]
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.
Solution 3:[3]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Duncan |
Solution 2 | Duncan |
Solution 3 | Kris Taylor |