Monday, August 20, 2007

Tips and Tricks: strings and formats

What if you want to output string data in a formatted fashion? You could use a format string in the same way that you would if writing PHP, C, Perl etc.. where %s is replaced by a string, %f is a float etc then you could end up with something like:
print "%10s is a filename"%stringvar

which would print the contents right-justified in a 10 character field. What if you wanted left-justified?
Well, then you would replace %10s with %-10s. Obvious, huh?

You could take advantage of some of the useful methods that Python strings own such as:
  • rjust - presents a number or string right-justified in a field of specified width (there is an ljust as well)
  • centre - presents the number or string centered in a filed of the specified field width
  • zfill - to present a number or string of a specified width padded out with zeroes as needed
and use them like this:
print "%s is a filename"%stringvar.rjust(10)

Of course, this is only useful if you are writing to a plain text file or a terminal. What if you are writing an HTML output? You could use named parameters like this..

print "%(noddy)s is a filename of %(max_len)d characters"%(max_len, noddy)

Notice the parameters are the wrong way round in the format specifier compared to the parameter list?
This can make constructing long format strings simpler. You can take this a step further by providing a dictionary instead of a list of parameters, like this

my_dict ={ 'name':'/var/log/message', 'code':1}
print "Examining %(name)s returned code %(code)i" %my_dict

Pyglet

Pyglet is a cross-platform windowing and multimedia library for Python.. uses OpenGL and has a clean API.

I'll take a look and write it up.