Let's say, I have a string:
> my_string = '{foo}/{bar}'
> my_string.format(foo='foo', bar='bar')
'foo/bar'
Right, cool. But in my case, I want to retrieve which are the keywords arguments in my_string
. I have done:
> ATTRS_PATTERN = re.compile(r'{(?P<variable>[_a-z][_a-z0-9]*)}')
> ATTRS_PATTERN.findall(my_string)
['foo', 'bar']
It's not very sexy. Do you have any better idea ?
You can use the
string.Formatter.parse
method. It splits the string into its literal text components and fields:To retrieve the names fields simply iterate over the result and collect the second field.
Note that this will include positional (both numbered and unnumbered) arguments as well.
Note that this does not include nested arguments:
If you want to get all named fields (assuming only named fields are used), you have to parse the second element in the tuple:
(This solution would allow arbitrarily deep format specifiers, while only one level would be sufficient).
Why reinvent the wheel?
string.Formatter
has the parse() function.