I like everything about python mostly thanks to its simplicity. I feel regular expressions have taken me away from my love for python far too many times. As such I wanted to extend the already existing string.Template class which lets me set variables in a string so that I can get values of an already existing string.
My first attempt works pretty well but has a few drawbacks:
import re
from string import Template
class TemplateX(Template):
def getvalues(self,Str):
regex = r""
skipnext = False
for i in self.template:
if skipnext == False:
if i != "$":
regex += i
else:
regex += r"(.+)"
skipnext = True
else:
skipnext = False
values = re.search(regex,Str).groups()
return values
temp = TemplateX(" Coords; $x;$y;$z;\n")
newstring = temp.substitute(x="1",y="2",z="3")
print newstring
values = temp.getvalues(newstring)
print values
newstring prints as: " Coords; 1;2;3;\n"
values prints as: ("1","2","3")
I am fine with losing some functionality of re for this simpler approach. My question is how can i add a little more functionality to getvalues to allow for variables in TemplateX to be more than 1 character (like the Template class and substitute allows). i.e. so that this works:
temp = TemplateX(" Coords; $xvar;$yvar;$zvar;\n")
newstring = temp.substitute(xvar="1",yvar="2",zvar="3")
print newstring
values = temp.getvalues(newstring)
print values
temp2 = TemplateX(" FindThese: $gx = $gy - $gz")
values2 = temp2.getvalues(" FindThese: $10000 = $10 - $5x")