paulgorman.org

Python Recipes

any() and all()

The any() and all() functions were introduced in Python 2.5.

#!/usr/bin/env python numbers = [1,10,100,1000,10000] if any(number == 10 for number in numbers): print '10 found.' numbers = [1,2,3,4,5,6,7,8,9] if all(number < 10 for number in numbers): print 'All number are under 10.'

Loop with enumerate()

#!/usr/bin/env python for i, color in enumerate(['red', 'blue', 'green']): print i, color

Loop dictionary with keys & values

#!/usr/bin/env python monsters = {'skeleton' : '1 HD', 'troll' : '6 HD'} for key, value in monsters.iteritems(): print key, value

Connect to a MySQL database

#!/usr/bin/env python import MySQLdb try: conn = MySQLdb.connect( host = 'myhost', user = 'myusername', passwd = 'mypassword', db = 'mydbname' ) cursor = conn.cursor() query = "SELECT alpha, beta FROM foo;" cursor.execute(query) rows = cursor.fetchall() for row in rows: print "%s, %s" % (row[0], row[1]) print cursor.rowcount + ' rows returned.' except MySQLdb.Error, e: print "Error %d: %s" % (e.args[0], e.args[1]) sys.exit(1) finally: if cursor: cursor.close() if conn: conn.close()

Regex on a Unicode file

#!/usr/bin/env python import codecs import unicodedata import re myfile = 'myfile.txt' updates = [] try: f = codecs.open(myfile, encoding='utf-16') for line in f: # Matching unicode is annoying. line = unicodedata.normalize('NFKD', line).encode('ascii', 'ignore') if re.match('\w{3,}\-*\w*\s+[0-9]+', line): updates.append(line.split()) except IOError, e: print "Error %d: %s" % (e.args[0], e.args[1]) sys.exit(1) finally: f.close()