formatting strings to have the same width

John Machin sjmachin at lexicon.net
Sat Mar 17 20:01:34 EDT 2007


On Mar 18, 10:17 am, "spohle" <spo... at gmail.com> wrote:
> sorry the code should read:
>
> foo = ["aaa", "1232"]
> for each in foo:
>     print each.center(10, " ") + " | "

Works OK for me on the console:

Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit
(Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> foo = ['123', '1234', '12345']
>>> for each in foo:
...     print each.center(10, ".") + " | "
...
...123.... |
...1234... |
..12345... |
>>>
>>> for each in foo:
...     print each.center(10, " ") + " | "
...
   123     |
   1234    |
  12345    |
>>> for each in foo:
...     guff = each.center(10, " ") + " | "
...     print guff + str(len(guff))
...
   123     | 13
   1234    | 13
  12345    | 13
>>>

Of course if I go into IDLE and change it to use a proportionally
spaced font (e.g. Arial), and do this:

>>> foo = ['lllll', 'mmmmm']
>>> for each in foo:
	print each.center(10, ' ') + ' | '


  lllll    |
  mmmmm    |
>>>

naturally they don't line up. If something like that isn't the cause
of your problem, you'll need to provide more information about your
environment.

HTH,
John




More information about the Python-list mailing list