Programming‎ > ‎

Python


My python snippets:

Get methods of module
>>> S = 'string'
>>> dir(S)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

Help on built-in function
>>> help(S.strip)
Help on built-in function strip:

strip(...)
    S.strip([chars]) -> str
    
    Return a copy of the string S with leading and trailing
    whitespace removed.
    If chars is given and not None, remove characters in chars instead.

Using Lists
>>> bob = ['Bob Smith', 42, 30000, 'software'] 
>>> sue = ['Sue Jones', 45, 40000, 'music']

Database list
>>> people = [bob, sue] 
>>> for person in people: print person 

['Bob Smith', 42, 30000, 'software'] ['Sue Jones', 45, 50000.0, 'music']

Field labels
We might try to associate names with relative positions by using the Python range built-in function, 
which builds a list of successive integers: 
>>> NAME, AGE, PAY = range(3)     # [0, 1, 2] 
>>> bob = ['Bob Smith', 42, 10000] 
>>> bob[NAME] 
    'Bob Smith' 
>>> PAY, bob[PAY]
    (2, 10000)

This really doesn't fix the problem, though, because we still have to index by position in order to fetch fields: 
>>> for person in people: 
        print person[0][1], 
        person[2][1] # name, pay 
        
    Bob Smith 10000
    Sue Jones 20000

Dictionaries
The list-based record representations in the prior section work, though not without some cost in terms of performance required to search for field names (assuming you need to care about milliseconds and such). But if you already know some Python, you also know that there are more convenient ways to associate property names and values. The built-in dictionary object is a natural: 
>>> bob = {'name': 'Bob Smith', 'age': 42, 'pay': 30000, 'job': 'dev'} 
>>> sue = {'name': 'Sue Jones', 'age': 45, 'pay': 40000, 'job': 'mus'}

Other ways to make dictionaries
>>> bob = dict(name='Bob Smith', age=42, pay=30000, job='dev') 
>>> bob {'pay': 30000, 'job': 'dev', 'age': 42, 'name': 'Bob Smith'}