使用python 模板,我可以生成输出。喜欢
>>> from string import Template
>>> s = Template('$who likes $what')
>>> s.substitute(who='tim', what='kung pao')
'tim likes kung pao'
如果我有字符串
'tim likes kung pao'
我怎样才能得到字符串tim
和kung pao
单独的变量?
您必须解析字符串。一种方法是使用正则表达式:
import re
m = re.match(r'(.*?) likes (.*?)', 'tim likes kung pao')
if m:
who, what = m.groups()
请注意,这可能会产生歧义;例如,如果你传递字符串“tim likes mary who like james”会发生什么?
一种方法是使用正则表达式:
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'
who, what = 'tim likes kung pao'.split(' likes ', 1)