Saturday, June 4, 2011

Python Tips & Tricks

Howdy hackers,

Some exciting news, Babolog is now Baybo -- just baybo.it

Here are a few helpful Python tips and tricks which I hope will help you save you time on menial tasks. If you have any feedback or suggestions, please let us know. We'd love to hear from you!

If you like these examples, consider searching for, "The Hacker's Guide to Python on Ubuntu" on http://baybo.it. The resource explains many of the lesser know features of the language which can save you a lot of time and hassle. HGPU should be available for purchase for $1.99 in the next few days so keep your eyes open.


Generate a List Containing All Letters of the Alphabet
>>> import string
>>> ' '.join(string.uppercase).split(' ')
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 
'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

Alternate Approach to Conditionals
# <expr> if <boolean> else <expr>
>>> True if (y == 1) else 3
3 
 
Iterate in Steps (with slicing) [start:stop:step] 
Iterate over a list from a [start:end:by-step-increment]. This syntax allows you to specify both a start and end position, as well as specify an 
increment for stepping through the iteration.   
 
# Strip the first two items and from the 8th element on
# and Iterate the remaining elements by increments / steps of 2 
>>> for item in range(9)[2:8:2] 
...    print item 
2 
4 
6 

Hope you found these tips helpful.

Sincerely,
- Michael E. Karpeles

No comments:

Post a Comment