JuanPablo
JuanPablo

Reputation: 24754

Python inverse template, get vars from a string

With python template, I can generate outputs. like

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

if I have the string

'tim likes kung pao'

how I can get the string tim and kung pao in separate variables ?

Upvotes: 1

Views: 178

Answers (3)

Jochen Ritzel
Jochen Ritzel

Reputation: 107608

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

Upvotes: 1

nneonneo
nneonneo

Reputation: 179392

You'd have to parse the string. One approach is to use a regular expression:

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

Note that this is subject to ambiguity; for example, what happens if you pass the string "tim likes mary who likes james"?

Upvotes: 2

NPE
NPE

Reputation: 500257

One way is to use 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'

Upvotes: 1

Related Questions