[Courses] [python] Lesson 9: More extras (requested topics)

Akkana Peck akkana at shallowsky.com
Fri Aug 12 23:17:08 UTC 2011


Today's lesson combines some more helpful string operations plus
two topics people said they wanted to hear about: web development
and GUI toolkits.

================ More string ops =======================

You've used split() and strip() on strings, but there are a few other
string functions you should know about.

First: joining strings. It happens fairly often that you have a list
like [ 'a', 'b', 'c', 'd' ] and you want to stick commas or spaces
between them to get something like "a, b, c, d". How do you do that?

The obvious thing to do is to loop over the list, something like:

thelist = [ 'a', 'b', 'c', 'd' ] 
s = ""
for x in thelist :
    s = s + "," + x

Except, oops! That produces "a, b, c, d," -- an extra comma. So you
have to do some heinous thing where you treat the first or last
element in the list differently. But fortunately, Python has a
shortcut way of doing that:

','.join(thelist)
' '.join(thelist)

The syntax is weird: you're making a string object out of the thing
you want to use to join everything, then calling that object's join()
function. It takes a while to get used to seeing that.

But if you can get past the wierd syntax, you'll find it super useful.

You can search for substrings:
if '://" in "http://example.com" :

or you can find exactly where they are:
s.find('pat')   # find the first occurence of pat in s
s.find('pat', start, end)

or replace parts of a string:
s.replace('X', 'Y')

Some other useful string operations (self-explanatory):
s.startswith("http://")
s.endswith(".html")
s.tolower(), s.toupper()

And, of course, lots of other stuff too:
http://docs.python.org/library/stdtypes.html#string-methods

================ Web development =======================

Someone asked about web development. I'm not going to go into a lot of
detail on that, but here are a few tips to get you started.

If you're writing CGI scripts in Python, you use cgi module, which
makes it easy to get values submitted from forms.

import cgi

print "Content-type: text/html\n"

fields = cgi.FieldStorage()
if "name" not in fields or "addr" not in fields:
    print "<H1>Error</H1>"
    print "Please fill in your name and address."
    return
print "<p>name:", fields["name"].value
print "<p>addr:", fields["addr"].value

If you want to download files from the web, use urllib2.
(I guess there was a urllib and nobody liked it. Or something.)
The basics are pretty easy:

import urllib2
response = urllib2.urlopen("http://linuxchix.org/")
if response.headers['content-type'].startswith("text")
    html = response.read()
    print html
else :
    print "It's not text!"

Of course, there are other modules for dealing with RSS, JSON,
databases and most other things you'll need for web programming.

================ Python GUI Apps =======================

Several people asked about Python GUIs. I'm going to cop out a little
here and point you to some articles I've already written -- partly
because that way there's more space for examples and screenshots.

You have three choices of toolkit for writing Python GUI apps:

- PyGTK: This comes preinstalled on most Linux distros. It's by far
the most polished and documented of the three options. However, it's
a minor pain to install on Windows (you have to install 4 packages from
two different places) and can be a major pain on Mac. I use PyGTK for
most of my own Python GUI development, but I have to keep in mind that
few non-Linux people will want to use it.
I wrote three Linux Planet articles on PyGTK:
http://www.linuxplanet.com/linuxplanet/tutorials/6750/1/
http://www.linuxplanet.com/linuxplanet/tutorials/6760/1/
http://www.linuxplanet.com/linuxplanet/tutorials/6771/1/

- PyTk: Some Python programmers consider this sort of a "native" GUI
toolkit for Python, and it comes bundled with Python for Windows, so
if you write in PyTk then Windows people will be able to use your app.
However, many Linux distros don't install it by default, so Linux
people won't be able to use your app without installing something;
and I've found the toolkit a bit rough and not all that well documented.
I don't have an article specifically on PyTk, but I do have an article
about writing a Twitter client where the UI is in PyTk:
http://www.linuxplanet.com/linuxplanet/tutorials/6792/1/
(Note: Twitter changed its authentication scheme since that was
published, so it won't work as a general Twitter client any more,
but you can use it for things like keyword searches.)

- PyQt: Being Qt, things look pretty and polished. But the toolkit
isn't nearly as well tested as the other two: I had a lot of trouble
getting things working well. Use it if you need to integrate with KDE
or if you're already a Qt fan, otherwise it may be more pain than it's
worth. I have a beginner article on PyQt:
http://www.linuxplanet.com/linuxplanet/tutorials/6967/1/

Someone also asked about GIMP-Python, and I have articles about that too:
http://www.linuxplanet.com/linuxplanet/tutorials/6720/1/
http://www.linuxplanet.com/linuxplanet/tutorials/6734/1/
There's a bit more information in my book (shameless plug),
"Beginning GIMP: From Novice to Professional": http://gimpbook.com/

================ Combining web and GUI ==================

If you can download files, and if you can bring up GUI windows, you
might wonder -- what about displaying them?

I mentioned early in the course that Python has an amazing number of
modules to do practically anything you can think of. Well, it turns
out there are Python bindings for WebKit, the browser used by
Konqueror, Chrome and lots of others. Which means it's amazingly
easy to write your own browser!

A while back, I used pywebkitgtk to write a simple presentation tool,
something I can use to display my slides at conferences instead of
using a full heavyweight browser like Firefox. I started with some of
the py-webkit-gtk sample code, and didn't have to make many changes
at all, and in 30 lines of code (including comments) I had a
presentation viewer. I blogged it:
http://shallowsky.com/blog/programming/webkit-presenter.html

=================== Homework ============================

I had so much fun reading the useful "solves real-world problems"
programs from lesson 8 that I'm going to keep it general again,
and say: 

Write either a web program (either CGI or client side) or a GUI
program, or both, to do something you find useful and/or fun.
Use docstrings in your functions.

Or, if you aren't interested in web or GUI programming, just write
any kind of fun or useful script!


More information about the Courses mailing list