Category Archives: Python

Cloning arrays in python

For single dimensions arrays:

a2 = a[:]
non-scalers within array will be copied as references. Does the same thing as copy.copy()

For multi dimension arrays:

import copy
a2 = copy.deepcopy(a)
non-scalers within array will be cloned as new objects

Python sprintf()

Python uses the % operator to do a sprintf() function.

“The %s brown %s” % (“quick”, “fox”)

Brackets can be omitted if there for single arguments

“The %s brown fox” % “fast”

You can view more PHP-Python statements here.

Python error/exception handling

This code quickly shows how to do basic error handling in python

try:
  # None + 1
  raise ZeroDivisionError
except ZeroDivisionError:
  print 'You cannot divide by zero!'
except:
  print sys.exc_info()[0]
else:
 print 'No errors raised'
finally:
 print 'Run Clean up actions'

Python eval

Generally, just use ‘exec’ statement instead of the ‘eval’ function

v = 1
exec 'v = 2'
print v

Python eval is a function meaning it doesn’t allow setting of variables. Usage is:
x = 1
print eval(‘x+1’)

Python MySQL utf connection + dictionary recordsets

# -*- coding: utf-8 -*-
import MySQLdb, MySQLdb.cursors
db_connection = MySQLdb.connect(user="root", passwd="pass",
db="mydb", cursorclass = MySQLdb.cursors.DictCursor,
use_unicode = True)
db = db_connection.cursor()
# assuming that id=1271 has a val that has utf "µ" in it
sql = """
SELECT *
FROM vals
WHERE id = 1271
""" % ()
db.execute(sql)
r = db.fetchall()[0]
val = r['val']
print val
print type(val)