2015-05-04 17 views
3

我想從格式化的Python字符串中獲取參數列表。從Python中獲取命名參數字符串

所以我的字符串看起來是這樣的:

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

我試圖做的是這樣的:

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

有沒有這樣做,沒有做我自己的功能的一種方式?我無法在String Formatter文檔中找到任何內容。

我正在使用Python3,但它會很好,如果它能在2.7以及。

回答

3

使用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'] 
+0

謝謝!這正是我所期待的。 – ferewuz