Archive for April 22nd, 2009

Python Tricks: Advanced String Formatting

April 22nd, 2009 | Category: python,python tricks

I ran across this a long time ago, never really used it till more recently, but it really shows the power and capability of Python.

So, say you have a big set of local variables which need to go into the string you are building, say for a YAPWF(Yet Another Python Web Framework).

Thats means you have this messy looking code:

s="%d%f" % (car, calc)

Its messy, because you’ve separated contextual information from the actual place that it matters, and if the string is very long and confusing, it gets messy, and opens you up to errors down the road. In addition, you are tied to having those variables exist locally.

However, there is a much, much nicer way to do this.

d={"number":100, "float":4.2, "status":"okay", "ph":8665782}
s="%(number)d%(float)f%(status)s%(ph)d" % d
print s
1004.2okay8665782

What this means is now you can throw in each of the relevant possible variables into the key that matters into a single dictionary object, and pass that around easily. The only thing you’re tied to now are the keys of the dictionary, giving you a bit of Adapter action.

Just one note, the format goes like this:

"%({key name}){format modifier}" % dictionary

As well, you can name the keys relevant names, like status, phone, etc, and your string formatting becomes a lot easier to read.

Comments are off for this post

Summer of Code: Start!

April 22nd, 2009 | Category: Uncategorized

So, I have been selected to work for the Google Summer of Code event, through Pygame/Python.

My project, while simple, will be a lot of fun. I will be wrapping ffmpeg for use as a movie module within Pygame. Ideally, the movie module will be usable outside of pygame. It’ll be a lot of work, 40 hours a week minimum, for three months, but it’ll be so much fun!

I’ll be using this blog to post regular updates on the progress of the code, alpha and beta releases, as well as calls for api suggestions.

1 comment