On Python String Templates

For many years, I’ve been doing string subsitution like this:

print "%s is %s" %("thrill","gone")

Which works, but can be confusing if you have a lot of subsitutions. Also, you can break the % section off from the rest of the line. So you can have a long, unreadable line in the middle of your neat Python code.

But I noted Python’s string templates quite some time ago but didn’t happen to have 2.4 on the systems that I wanted to use it on. Finally, I have 2.4.1 on enough systems and, just today, I found the perfect thing to use them for — some help in XML parsing with ElementTree

from string import Template
import cElementTree as ET

gpNS=Template("{http://www.groundspeak.com/cache/1/0}$tag")
gpxNS=Template("{http://www.topografix.com/GPX/1/0}$tag")

gpx = ET.parse("some.gpx")

root = gpx.getroot()

longDescTag = gpNS.substitute(tag="long_description")
nameTag = gpxNS.substitute(tag="name")
gpxDescTag = gpxNS.substitute(tag="desc")
urlTag = gpxNS.substitute(tag="url")
wptTag = gpxNS.substitute(tag="wpt")

outLine=Template("$lat,$lon,$name,$desc,$url")

for wpt in root.findall(".//"+wptTag):
     print outLine.substitute(lat=wpt.get("lon"),
                                     lon=wpt.get("lat"),
                                     name=wpt.findtext(nameTag),
                                     desc=wpt.findtext(longDescTag),
                                     url=wpt.findtext(urlTag))


This, I think, makes adding the namespace stuff that ElementTree requires a lot more managable. And having a ton of options on the output makes this a perfect case for a Template.

Leave a Reply

You must be logged in to post a comment.