[Tutor] String format question

Jeff Shannon jeff@ccvcorp.com
Wed Nov 27 16:52:02 2002


andy surany wrote:

> Thanks Jeff.
>
> Maybe I can explain it a little better....
>
> I am obtaining data from multiple databases. Any data which is not in
> character format is converted. The data is then formatted into a single
> string which is displayed in a scrolled list.

Okay, then my suggestion about a list of tuples is probably not worth the
effort.  Figured I'd mention the possibility anyhow.


> I tried using the string formatting operator as well as .ljust. The
> problem is that these are true "formatting" controls - which are good
> for print, etc. But they are invalid (lost) when concatenating a string.
> Or at least they are lost the way that I have tried to do it.....

If you use string formatting as I showed, then you end up with a single
string (or rather, a list of strings) with enough spaces added to start each
element at the same position.  This is, as near as I can tell, exactly what
you say you want.

>>> a = ['aaa', 'a', 'aa']
>>> b = ['b', 'bb', 'bbb']
>>> c = ['cc', 'ccc', 'c']
>>> nrecs = len(a)
>>> optionlist = ["%-5s %-5s %-5s" % (a[i], b[i], c[i]) for i in
range(nrecs)]
>>> for line in optionlist:
...  print line
...
aaa   b     cc
a     bb    ccc
aa    bbb   c
>>>

Count 'em, each 'c' begins at the 12th character.

Next question, then, would be how is your data being displayed?  Does this
ScrolledList control use a proportional font, maybe?  If so, then no amount
of text-based formatting is going to give you even columns.  (Spaces will be
narrower than most printable characters, and even those will vary in width,
so predicting how many spaces need to be added to make different lines fall
into place is very difficult.)  You'll have to use the GUI functions of the
list control, or use several linked controls.  (Unless, of course, you can
coerce the control into using a fixed-width font...)  What toolkit are you
getting this ScrolledList from?

Jeff Shannon
Technician/Programmer
Credit International