[Tutor] re: String formatting

Charlie Clark charlie@begeistert.org
Sun, 17 Mar 2002 15:09:40 +0100


On 2002-03-17 at 10:07:04 [+0100], tutor-request@python.org wrote:
> > print "%-10s %-60s" % (badword, line)
> >
> > The % syntax is probably overkill for this, though, and since it's not
> > all that easy to use unless you already know C (which is where it comes
> > from) you can probably live without it for now.

C-type formatting is really easy to trip over if you're not used to it; I'm not ;-). It doesn't feel like Python to me but it's obviously very useful to some people. It's quite useful for building SQL statements for example.

Concatenating objects either with "+" or using commas is really legible but often tiresome to type. I usually find I start with something like that and then move onto to something more efficient. One method which I didn't mentioned is using string.join() to do string formatting.
>>> data = ['mary', 'had', 'a', 'little', 'lamb']
>>> ",".join(data)
>>> 'mary', 'had', 'a', 'little', 'lamb'

Can be combined with great effect with other string methods and the ability to get a string representation from any Python data type is a godsend.

Charlie