how to enumerate string placeholders?
<p>I'd like to know what's the best way to enumerate placeholders from strings, I've seen there is already another post which asks <a href="http://stackoverflow.com/questions/14061724/how-can-i-find-all-placeholders-for-str-format-in-a-python-string-using-a-regex">how-can-i-find-all-placeholders-for-str-format-in-a-python-string-using-a-regex</a> but I'm not sure the answers provided are giving me exactly what I'm looking for, let's examine this little test:</p>

<pre><code>import string

tests = [
    ['this is my placeholder 1 {} and this is the 2 {}', 2],
    ['another placeholder here {} and here \"{}\"', 2]
]
for s in tests:
    num_placeholders = len([
        name for text, name, spec, conv in string.Formatter().parse(s[0])])
    if num_placeholders != s[1]:
        print("FAIL: {0} has {1} placeholders!!! excepted result {2}".format(
            s[0], num_placeholders, s[1]))
</code></pre>

<p>It seems <a href="https://docs.python.org/2/library/string.html#string.Formatter" rel="nofollow">string.Formatter</a> is not giving me the expected answer I'm looking for:</p>

<pre><code>FAIL: another placeholder here {} and here "{}" has 3 placeholders!!! excepted result 2
</code></pre>

<p>Because you are ignoring the other elements on the tuple that <code>parse(s)</code> returns:</p>

<pre><code>&gt;&gt;&gt; import string
&gt;&gt;&gt; 
&gt;&gt;&gt; tests = [
...     "{} spam eggs {}",
...     "{0} spam eggs {1}",
...     "{0:0.2f} spam eggs {1:0.2f}",
...     "{{1}} spam eggs {{2}}"
... ]
&gt;&gt;&gt; for s in tests:
...     print [x for x in string.Formatter().parse(s)]
... 
[('', '', '', None), (' spam eggs ', '', '', None)]
[('', '0', '', None), (' spam eggs ', '1', '', None)]
[('', '0', '0.2f', None), (' spam eggs ', '1', '0.2f', None)]
[('{', None, None, None), ('1}', None, None, None), (' spam eggs {', None, None, None), ('2}', None, None, None)]
</code></pre>

<p>Edit: I see what you mean now. Yes, the interpretation of the parsing is not intuitive nor obvious. The length of the returned list is not for the count of placeholders but for the count of literal portions of strings, including an empty string at the start but not including the empty string at the end. And each element also contains the format of what follows. For example:</p>

<pre><code>&gt;&gt;&gt; list(string.Formatter().parse('{}'))
[('', '', '', None)]
</code></pre>

<p>This is the base case, and there is one single empty string of literal text. There are actually two empty strings, but the parser does not include the last empty string.</p>

<pre><code>&gt;&gt;&gt; list(string.Formatter().parse('a {}'))
[('a ', '', '', None)]
</code></pre>

<p>Now we have the same as before: only one literal string "a " with nothing that follows. Since there is nothing that follows the format bracket then there is no element.</p>

<pre><code>&gt;&gt;&gt; list(string.Formatter().parse('{} b'))
[('', '', '', None), (' b', None, None, None)]
</code></pre>

<p>This is the interesting case: since the format bracket is at the start, the first literal string is an empty literal string, and follows the string " b". </p>

<pre><code>&gt;&gt;&gt; list(string.Formatter().parse('a {1} b {2} c'))
[('a ', '1', '', None), (' b ', '2', '', None), (' c', None, None, None)]
</code></pre>

<p>This one is a very complete example. We have three literal string pieces: <code>['a ', ' b ', ' c']</code>. The confusing part is that the specific format information for the format brackets {} is merged with the previous literal string element.</p>

<p>Edit2:</p>

<pre><code>&gt;&gt;&gt; [x[0] for x in string.Formatter().parse('another placeholder here {} and here \"{}\"')]
['another placeholder here ', ' and here "', '"']
</code></pre>

<p>We follow the same logic here. The quotes are just raw literal string, we can change the quotes to something else:</p>

<pre><code>&gt;&gt;&gt; [x[0] for x in string.Formatter().parse('another placeholder here {} and here qqq{}www')]
['another placeholder here ', ' and here qqq', 'www']
</code></pre>

<p>If you only consider the 'name' from each returned tuple you only get the literal string. Between each individual element lies the format placeholder. </p>

<p>You need to understand the result of the parse() from the point of view of formatting the string. This result makes it simple to produce the output formatted string. For example:</p>

<pre><code>&gt;&gt;&gt; [x for x in string.Formatter().parse('a{}')]
[('a', '', '', None)]
&gt;&gt;&gt; [x for x in string.Formatter().parse('a')]
[('a', None, None, None)]
</code></pre>

<p>With this logic you can count the number of placeholders in a format string like this:</p>

<pre><code>&gt;&gt;&gt; def count_placeholders(fmt):
...     count = 0
...     L = string.Formatter().parse(fmt)
...     for x in L:
...         if x[1] is not None:
...             count += 1
...     return count
... 
&gt;&gt;&gt; count_placeholders('')
0
&gt;&gt;&gt; count_placeholders('{}')
1
&gt;&gt;&gt; count_placeholders('{}{}')
2
&gt;&gt;&gt; count_placeholders('a {}{}')
2
&gt;&gt;&gt; count_placeholders('a {} b {}')
2
&gt;&gt;&gt; count_placeholders('a {} b {} c')
2
</code></pre>

python string