News

Another ten essential Python tips

To compliment our 'ten essential Python tips for beginners' and 'ten more essential Python tips' features, we've compiled yet another collection of ten gems to make your Python experience that much more worthwhile…

Python is one of the most popular programming languages in the open source space. Look around and you will find it running everywhere, from various configuration tools to XML parsing. To compliment our ‘ten essential Python tips for beginners‘ and ‘ten more essential Python tips‘ features, we’ve compiled yet another collection of ten gems to make your Python experience that much more worthwhile… Any bets on whether we’ll do another?

Converting any charset to UTF-8
You can use the following function to convert any charset to UTF-8.

data.decode(“input_charset_here”).encode(‘utf-8’)

Removing duplicates from lists
If you want to remove duplicates from a list, just put every element into a dict as a key (for example with ‘none’ as value) and then check dict.keys().

from operator import setitem
def distinct(l):
d = {}
map(setitem, (d,)*len(l), l, [])
return d.keys()

Do-while loops
Since Python has no do-while or do-until loop constructs (yet), you can use the following method to achieve similar results:

while True:
do_something()
if condition():
break

Detecting system platform
To execute platform-specific functions, it is very useful to detect the platform on which the Python interpreter is running. You can use ‘sys.platform’ to find out the current platform.

[Example On Ubuntu Linux]
>>> import sys
>>> sys.platform
‘linux2’

[On Mac OS X Snow Leopard]
>>> import sys
>>> sys.platform
‘darwin’

×