Python Tricks



- Python Types


For types in Python see: -Python Types-

* Strings

dir(str)          # show all attributes and methods of str
str.lower()       # Change string to lowercase
str.rstr()        # Get rid of problematic carriage returns \r and linefeeds \n


* Lists

dir(list)         # show all attributes and methods of list
list.append(x)    # Add item to end of list
list.insert(i,x)  # Insert item at give position i

-All methods for the list object-
-Google for devs-


- Python Built-in Functions -


For builtins go to : -Python Builtins-

* zip

It's a function that returns a list of tuples from two single lists, for example:
x = [1, 2, 3]
y = [A, B, C]
zipped = zip(x,y)
print zipped
[(1,A),(2,B),(3,C)]

- General Tricks -


python -m pdb example1.py                 # To invoke the debugger to debug scripts  
python -c "c = 3.6323 + 3.8423; print c"  # One liners

- Setting up Python


To be able to manipulate data files easily in python, as it would be done in octave or R, one first has to "install" Numpy, and Matplotlib. In ubuntu it's easy and one can do it with apt-get install.
Another program which is useful is:
sudo apt-get install python-setuptools

With this installed it's easy to integrate python libraries, for example pymc:
easy_install pymc



- Python Links


* Scripting
* Tricks with lists, dictionaries, functions.