开发者

Generate values for str.format style template strings from formatted output

This might seem like a wierd requirement, but I am looking for a good implementation to do this.

I have a dict like

vals = dict(red='#F00', green='#0F0', blue='#00F')

and a string like

tpl = '{red开发者_如何学JAVA}:{green}:{blue}'

and the str.formatted output

output = tpl.format(**vals)

All is well till here. However, I now need to do the reverse of this. I have to turn a string like '#F00:#0F0:#00F' into a dict of the values that we previously started with. Of course, I could just split and strip the string and take the values I need, but it will fail in the event the tpl string should change.

Any good ideas on how I can do this (If it can even be done, that is)?


You can use regular expressions. (And maybe then you'll have two problems.)

>>> import re
>>> pattern = re.compile('(#[\da-fA-F]{3})')
>>> l = pattern.findall(output)
['#F00', '#0F0', '#00F']
>>> dict(zip(('red', 'green', 'blue'), l))
{'blue': '#00F', 'green': '#0F0', 'red': '#F00'}
>>>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜