Python Notes

This post conatins Python programming notes, from the Python tutorial that is offered by Google

Basics

def Hello(name):
    a = 'hello'

How python works

Strings slice

>>> a = 'Hello'
>>> a
'Hello'
>>> a[1:3]
'el'
>>> a[1:2]
'e'
>>> a[1:5]
'ello'
>>> a[1:]
'ello'
>>> a[:5]
'Hello'
>>> a[:]
'Hello'

Negatives

>>> a = 'Hello'
>>> a[-1]
'o'
>>> a[-3:]
'llo'
>>> a[-3:-1]
'll'

Lists

Sorting

Custom sorting

>>> sorted(a,key=len)
['d', 'a', 'dc', 'aa', 'ccc']
>>> def last(s): return s[-1]

>>> sorted(a,key=last)
['a', 'aa', 'ccc', 'dc', 'd']
split, join
>>> ':'.join(a)
'z:d:dc:a:aa'
>>> '\n'.join(a)
'z\nd\ndc\na\naa'
>>> ':'.join(a)
'z:d:dc:a:aa'
>>> b = ':'.join(a)
>>> b.split(':')
['z', 'd', 'dc', 'a', 'aa']

Tuple

>>> a = (1,3,3)
>>> a
(1, 3, 3)
>>> len(a)
3
>>> a[0]
1
>>> a[0]=2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
Sort by one thing and then sort by other 
Write key function that returns a tuple
>>> a = [(1,"b"),(2,"a"),(1,"a")]
>>> a
[(1, 'b'), (2, 'a'), (1, 'a')]
>>> sorted(a)
[(1, 'a'), (1, 'b'), (2, 'a')]
Parallel assignment 
>>> (x,y) = (1,2)

HashTable , /Dictionary

>>> d ={}
>>> d['a'] = 'alpha'
>>> d['a']
'alpha'
>>> d['B']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'B'

get(),keys(),items()

d.get()
>>> d.get('a')
'alpha'
>>> d.get('f')
how to find if something is in dict
‘a’ in d
True
.keys()

>>> d.keys()
['a']
>>> d['b'] = 'beta'
>>> d.keys()
['a', 'b']
values()
>>> d.values()
['alpha', 'beta']

looping

>>> for k in sorted(d.keys()): print 'key:',k,'->',d[k]
... 
key: a -> alpha
key: b -> beta
d.items()
    >>> d.items()
[('a', 'alpha'), ('b', 'beta')]
>>> for tuple in d.items(): print tuple
... 
('a', 'alpha')
('b', 'beta')

Files

Regular Expression

\S non whitespace
\s whitespace
\d digit 0-9
\w word character a-z A-Z 0-9

Email example

>>> m = re.search(r'([\w.]+)@([\w.]+)','egrreg gjkenrkj@snfjkv.com erngjk @ ')
>>> m
<_sre.SRE_Match object at 0xb7467800>
>>> m.group()
'gjkenrkj@snfjkv.com'
>>> m.group(1)
'gjkenrkj'
>>> m.group(2)
'snfjkv.com'
>>> m = re.search(r'([\w.]+)@([\w.]+)','egrreg gjken.rkj@snfjkv.com erngjk @ ')
>>> m
<_sre.SRE_Match object at 0xb7467140>
>>> m.group(1)
'gjken.rkj'
>>> m.group(2)
'snfjkv.com'
findall()
    >>re.findall(r'[\w.]+@[\w.]+','egrreg@fmail.com gjken.rkj@snfjkv.com erngjk @ ')
['egrreg@fmail.com', 'gjken.rkj@snfjkv.com']

 re.findall(r'([\w.]+)@([\w.]+)','egrreg@fmail.com gjken.rkj@snfjkv.com erngjk @ ')
[('egrreg', 'fmail.com'), ('gjken.rkj', 'snfjkv.com')]

Flags

Modules

Exceptions

def cat(filename):
  try:
    f = open(filename, 'rU') #U ignare dos line ending unix
    print '-----',filename
    text = f.read() #having just 1 string
    print text
    f.close()
  except IOError:
    print 'No File',filename 
def main():
  args = sys.argv[1:]
  for arg in args:
    cat(arg)

Modularity

urllib