Since I'm new to Python, I'm using this as a place to jot down tips and neat ways to do things. I doubt anything here will be groundbreaking, but for a newbie, might be of some use. I'm using Python 2.5 - I have no idea if this works for previous versions.
String Concatenation
# rather than this string s = "" for x in list: s += xdo this
s = "".join(list)
if generating bits sequentially, do this
slist = [some_function(x) for x in list]
s = "".join(slist)
Formatting & Concatenation
# don't do this html = "" + head + body + footer + "" # do this html = "%s %s %s" % (head, body, footer) # or this using a dictionary html = "%(head)s %(body)s %(footer)s" % vars()
Finding a string
# nope bleh = "hi there!" if bleh.find("hi") > -1: # ... # yep if "hi" in bleh: ...
Lists
Similar to the lambda statement:numbers = [1,2,3,4,5] squares = [number*number for number in numbers] >>> [1,4,9,16,25]
Filtering:
numbers = [1,2,3,4,5] under_4 = [number for number in numbers if number < 4] >>> [1,2,3]
Filter and Map:
numbers = [1,2,3,4,5] square_under_4 = [number*number for number in numbers if number < 4] >>> [1,4,9]
Getting the index in a for loop
list = ['a','b','c','d'] for index, chr in enumerate(list): ...
See if something's in a list
list = [1,2,3,4] if 1 in list: print '%i is in the list' % 1
Any and All over lists
numbers = [1,2,3,4,5] if any(number < 4 for number in numbers): print 'less than 4: ' + number if all(number < 10 for number in numbers): print 'great success!'
Lambda
squares = map(lambda a: a*a, [1,2,3,4,5]) >>> [1, 4, 9, 16, 25]
Meta Stuff
What methods doesstr
have?
dir(str)
What's the str.find()
method all about?
print getattr(str, 'find').__doc__
Dictionaries
# can do this d = { 'a': 1, 'b': 2, 'c': 3 }can also do this
d = dict(a=1, b=2, c=3)
Truthiness
has_email = True name = person.email if has_email else 'Anonymous'different way, kinda like C ternary statement (a = b ? c : d)
name = has_email and person.email or 'Anonymous'