Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting named parameters from Python string [duplicate]

I am trying to get a list of parameters from a formatted Python string.

So my string looks something like this:

formatted_string = 'I am {foo}. You are {{my}} {bar}.'

I am trying do to something like:

get_named_parameters(formatted_string) = ['foo', 'bar']

Is there a way of doing that without making my own function? I couldn't find anything in String Formatter docs.

I am using Python3, but it would be nice if it would work in 2.7 as well.

like image 845
ferewuz Avatar asked Nov 27 '25 23:11

ferewuz


1 Answers

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']
like image 76
vaultah Avatar answered Nov 30 '25 11:11

vaultah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!