Getting named parameters from Python string
I am trying to get a list of parameters from a Python formatted string.
So my line looks something like this:
formatted_string = 'I am {foo}. You are {{my}} {bar}.'
I am trying to do something like:
get_named_parameters(formatted_string) = ['foo', 'bar']
Is there a way to do this without my own function? I couldn't find anything in the String Formatter docs.
I'm using Python3, but it would be nice if it worked in 2.7 as well.
+3
source to share
1 answer
Using string.Formatter.parse
:
In [7]: from string import Formatter
In [8]: [x[1] for x in Formatter().parse(formatted_string) if x[1] is not None]
Out[8]: ['foo', 'bar']
+3
source to share