BPL BPL - 3 months ago 13
Python Question

how to enumerate string placeholders?

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 how-can-i-find-all-placeholders-for-str-format-in-a-python-string-using-a-regex but I'm not sure the answers provided are giving me exactly what I'm looking for, let's examine this little snippet:

import string

tests = [
"{} spam eggs {}",
"{0} spam eggs {1}",
"{0:0.2f} spam eggs {1:0.2f}",
"{{1}} spam eggs {{2}}"
]
for s in tests:
print [name for text, name, spec, conv in string.Formatter().parse(s)]


It seems string.Formatter gives the right number of placeholders and in some cases gives some information
['0', '1']
:

['', '']
['0', '1']
['0', '1']
[None, None, None, None]


But it feels like in other cases doesn't provide complete information about the placeholders (at least the way I'm doing), so... am I missing something?

EDIT:

import string

tests = [
'{} and \"{}\"'
]
for s in tests:
print [name for text, name, spec, conv in string.Formatter().parse(s)]


It's giving me
['', '', None]
but I'd like to know there is only 2 placeholders

vz0 vz0
Answer

Because you are ignoring the other elements on the tuple that parse(s) returns:

>>> import string
>>> 
>>> tests = [
...     "{} spam eggs {}",
...     "{0} spam eggs {1}",
...     "{0:0.2f} spam eggs {1:0.2f}",
...     "{{1}} spam eggs {{2}}"
... ]
>>> 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)]
Comments