In python I can do the following:
who = "tim"
what = "cake"
print "{0} likes {1}".format(who, what)
to yield "tim likes cake".
However the inverse operation is not as straightforward since I need to use regular expressions. I mean, to parse a string of known structure and extract the portions I know it contains, and store them into my variables. This extraction I perform by:
import re
expression = "([a-z]*) likes ([a-z]*)"
input_line = "tim likes cake"
who, what = re.search(expression, inputline).groups()
which is neat enough for small amount of parameters, but it has two main drawbacks for me compared to my idea of "ideal inverse" to format():
- Parameters extracted are always strings, they need to be converted to float with extra lines. Format handles internally the conversion needed, from any value to string.
- I need to define different templates for input and output, because the input template in regular expression form "([a-z]*) likes ([a-z]*)" cannot be reused for the "exporting" of the data, in the format function.
So, my question is, does a function like this exists, which would parse automatically the string and get the values the same way as we print them to the string, following almost the same syntax like
"{0} likes {1}".extract(who,what,input_line="tim likes cake")
I am aware I can create my custom "extract" function which behaves as desired, but I don't want to create it if there is already one available.