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
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
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′)
re.DOTALL / re.S – means dot will match newlines
re.MULTILINE / re.M – means that ^$ will only match start and end of string. By default they match start and end of each line
match = re.search(r'^(.+lorem ipsum)(.+)(donor kebab.+)$', s, re.DOTALL + re.MULTILINE)
# -*- 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)
# -*- coding: utf-8 -*-
import xml.dom.minidom, codecs
impl = xml.dom.minidom.getDOMImplementation()
dom = impl.createDocument(None, "root", None)
root_el = dom.documentElement
ascii_el = dom.createElement('ascii')
root_el.appendChild(ascii_el)
ascii_el.appendChild(dom.createTextNode('abc'))
utf_el = dom.createElement('utf')
root_el.appendChild(utf_el)
utf_el.appendChild(dom.createTextNode(unicode('µ 6000', 'utf-8')))
# There's a couple of ways of dealing with output:
if True:
# Will write a utf encoded file without BOM
# <?xml version="1.0"?>
# Will print "µ" to the console
# type(xmlstr) == 'unicode' i.e. unicode string
xmlstr = dom.toxml()
f = codecs.open('utf_test.xml', 'w', 'utf-8')
f.write(xmlstr)
f.close()
print xmlstr
print type(xmlstr)
else:
# Will write a utf encoded file without BOM (same as above)
# <?xml version="1.0" encoding="utf-8"?>
# Will print "??" to the console
# type(xmlstr) == 'str' -- i.e. byte string
xmlstr = dom.toxml('utf-8')
f = open('utf_test.xml', 'w')
f.write(xmlstr)
f.close()
print xmlstr
print type(xmlstr)
Instead of hash like access i.e. val = hash['key']
You can achieve a prettier val = obj.key :
class Obj:
..def add(self, k, v):
....self.__dict__[k] = v
o = Obj()
o.add(key, val)