Archive

Posts Tagged ‘tip’

for / else and try / except / else

June 17, 2016 1 comment

Problem
What is that “else” in a for loop? And that “else” in an exception handler?

Solution
They can be confusing but in this thread I found a perfect way to remember what they mean. Asdayasman suggests that we should always annotate these “else” branches:

for _ in []:
    ...
else:  # nobreak
    ...

try:
    ...
except:
    ...
else:  # noexcept
    ...

To be honest, IMO it is best to avoid for / else completely.

Categories: python Tags: , , ,

endswith also accepts a tuple

November 7, 2015 1 comment

Have you ever written something like this?

fname = 'movie.avi'
if fname.endswith('avi') or fname.endswith('mp4'):
    print("It's a movie.")

The function endswith also accepts a tuple. Just saying.

fname = 'movie.avi'
if fname.endswith(('avi', 'mp4')):
    print("It's a movie.")

Meaning: if it ends as ‘aviormp4‘, then…

This also works with startswith, of course.

Thanks to one of my students, Marton Sz. who solved one of his exercises using this trick.

Categories: python Tags: , , ,

Python PIL : IOError: decoder jpeg not available

December 2, 2012 Leave a comment

Problem
Working with JPG files, PIL drops the following error:

Python PIL : IOError: decoder jpeg not available

Solution

sudo pip uninstall PIL
sudo apt-get install libjpeg8-dev
sudo pip install PIL

Found here.

Categories: python Tags: , , , ,

Print unicode text to the terminal

September 2, 2012 2 comments

Problem
I wrote a script in Eclipse-PyDev that prints some text with accented characters to the standard output. It runs fine in the IDE but it breaks in the console:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xf3' in position 11: ordinal not in range(128)

This thing bugged me for a long time but now I found a working solution.

Solution
Insert the following in your source code:

import sys
reload(sys)
sys.setdefaultencoding("utf-8")

I found this trick here. “This allows you to switch from the default ASCII to other encodings such as UTF-8, which the Python runtime will use whenever it has to decode a string buffer to unicode.”

Related

Categories: python Tags: , , , ,

Template

September 21, 2010 1 comment

Here is the classical “Hello, World!” script in Python. It can be used as a template for writing a new script:

#!/usr/bin/env python

# DESCRIPTION:   hello world
# DATE:          2010.09.21. (yyyy.mm.dd.)

print "Hello, World!"

Tip: If you want to insert source code in your blog at WordPress.com, check out this post: Code » Posting Source Code.

Update (20110503): For a more professional template, see this post, where Guido tells us how he writes his main() functions.

Categories: python Tags: ,