开发者

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

开发者 https://www.devze.com 2023-03-31 11:57 出处:网络
This might seem like a wierd requirement, but I am looking for a good implementation to do this. I have a dict like

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

精彩评论

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

关注公众号