Python

Magic with strings

Formatting a string


this site gives a nice overview of string formatting. Here are some basic examples:
## formatting floats
p = 0.012445354
s = "p = %1.2f"%p ## s equals "p = 0.01"

XML and Python

Importing and exporting XML files with Python is well documented on the world wide web of the internet, but here is a short 'reference card' of the stuff I use and then forget all the time. Click here for more.

Importing an XML file

import xml.etree.ElementTree as ET
tree = ET.parse("data.xml") ## suppose that your folder contains some xml file called data.xml
root = tree.getroot()
 
print root.tag ## the tag of an element
print root.attrib["date"] ## the attributes are stored in a dictionary
 
for child in root: ## we can iterate over the child-nodes of root
    print child.text ## print any text contained by child

Searching for data in the tree

stuffs = root.findall("stuff") ## find all elements with tag "stuff" in the tree
chriss_stuffs = root.findall("stuff[@owner='chris']") ## find all elements with tag "stuff" and attribute "owner" equal to "chris"