如何从python中的字符串中检索关键字参数? [英] How retrieve keyword arguments from a string in python?
本文介绍了如何从python中的字符串中检索关键字参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
比方说,我有一个字符串:
Let's say, I have a string:
> my_string = '{foo}/{bar}'
> my_string.format(foo='foo', bar='bar')
'foo/bar'
对,很酷.但就我而言,我想检索my_string
中的关键字参数.我已经完成了:
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 ?
推荐答案
为什么要重新发明轮子? string.Formatter
具有 parse()函数.
Why reinvent the wheel? string.Formatter
has the parse() function.
>>> import string
>>> [a[1] for a in string.Formatter().parse('{foo}/{bar}')]
['foo', 'bar']
这篇关于如何从python中的字符串中检索关键字参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文