I campi di formato sono significativi solo per l'operatore %
, non per la stringa stessa. Quindi, non esiste un attributo come str.__format_fields__
a cui è possibile accedere per ottenere i nomi dei campi.
Direi che l'utilizzo di Regex è in realtà l'approccio corretto in questo caso. Si può facilmente utilizzare re.findall
per estrarre i nomi:
>>> import re
>>> x = "hello %(foo)s there %(bar)s"
>>> re.findall('(?<!%)%\(([^)]+)\)[diouxXeEfFgGcrs]', x)
['foo', 'bar']
>>>
seguito è una spiegazione del modello:
(?<!%) # Negated look-behind to make sure that we do not match %%
% # Matches %
\( # Matches (
( # Starts a capture group
[^)]+ # Matches one or more characters that are not)
) # Closes the capture group
\) # Matches)
[diouxXeEfFgGcrs] # Matches one of the characters in the square brackets
E '[molto facile] (https://docs.python.org/2/library/string.html#string.Formatter) se puoi passare alla nuova formattazione di stile. –
non proprio un'opzione, sfortunatamente – qhfgva