Wednesday, December 19, 2012

Learning Python (1): Reading Book "Dive into Python 3"

I am reading the book "Dive into Python 3" now, which has HTML version for free. This is an advanced book, and actually the first two chapters almost cover all the syntax talked in "Learn to Program". One of the book's drawback is it doesn't have exercise, so I have to find some interesting projects from other places.

Comprehension

The first special thing I learn from the book is comprehension. It's like a filter that can select elements from list, dictionary or set. It's pretty much like for-if-else loop, but more compact.

Example
Replace each lowercase letter in a string by the letter two places after it. It can be achieved by one-line code in Python:

a = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."
print(''.join([chr(ord('a') + (ord(x) - ord('a') + 2) % 26) if x in string.ascii_lowercase else x for x in a]))

Another way is to use maketrans and translate function:
table = a.maketrans(string.ascii_lowercase, string.ascii_lowercase[2:] + string.ascii_lowercase[:2])
print(a.translate(table))


This example is from level 1 of Python Challenge, which I'm currently using and enjoying as exercise.


No comments:

Post a Comment