Tuesday, August 16, 2011

Some useful python tricks

Emulate Conditional Operator x ? y : z
In C-like programming languages, '? :' is one of the most popular operators. It's not supported by python, but it's pretty easy to emulate in python by:
x and y or z
It's quite common to make a http API call by Get or Post methods in python. It can be easily done with the urllib module.
import urllib
params = [("name", "Jonathan"),("email", "Jason@gmail.com")]
encoded_params = urllib.urlencode(params)
baseurl = "http://www.google.com/search?"#remove '?' for a POST call
url = baseurl + encoded_params 
read_data = urllib.urlopen(url).read()
For example, the final URL for a GET request will be:
Check if a String Contains a Substring
string = 'Hi there'
if string.find('Hi') != -1:
    print 'Success!'
Instead of the above one, we do it with in operator:
string = 'Hi there'
if 'Hi' in string:
    print 'Success!'
Lambda Functions
>>> map(lambda a: a*a, [1,2,3,4,5])
... [1, 4, 9, 16, 25]
Map and Filter a List
numbers = [1,2,3,4,5]
squares = map(lambda x: x*x, filter(lambda x: x < 4, numbers))
numbers = [1,2,3,4,5]
squares = [number*number for number in numbers if number < 4]
Match the End of Line (EOL)
Sometime we need to match a whole line including the EOL mark. The problem is EOL has different representations in different operating systems. It's '\r\n' in Windows systems but '\n' in Linux-like systems. To match a whole line by Regular Expression will be tricky. For example, we want to remove a line ending with a exclamation mark, like "Hello World!" (EOL is not shown), we should do as followings:
import re
example_re = re.compile(r'^.*\r?\n') # ? marks \r to be optional
messages = example_re.sub('', messages)

No comments:

Post a Comment