Python逆模板,从字符串中获取变量

时间:2013-09-06 14:10:41

标签: python string templates

使用python template,我可以生成输出。喜欢

>>> from string import Template
>>> s = Template('$who likes $what')
>>> s.substitute(who='tim', what='kung pao')
'tim likes kung pao'

如果我有字符串

'tim likes kung pao'

如何在单独的变量中获取字符串timkung pao

3 个答案:

答案 0 :(得分:2)

你必须解析字符串。一种方法是使用正则表达式:

import re
m = re.match(r'(.*?) likes (.*?)', 'tim likes kung pao')
if m:
    who, what = m.groups()

请注意,这可能会有歧义;例如,如果你传递字符串“蒂姆喜欢喜欢詹姆斯的玛丽”会发生什么?

答案 1 :(得分:1)

一种方法是使用regular expressions

In [8]: import re

In [9]: who, what = re.match(r'(.*) likes (.*)', 'tim likes kung pao').groups()

In [10]: who
Out[10]: 'tim'

In [11]: what
Out[11]: 'kung pao'

答案 2 :(得分:1)

who, what = 'tim likes kung pao'.split(' likes ', 1)