[Tutor] Help with strings and lists
Alan Collins
online330983 at telkomsa.net
Fri Jul 14 19:36:01 CEST 2006
> Date: Fri, 14 Jul 2006 12:12:42 +0200
> From: J?nos Juh?sz <janos.juhasz at VELUX.com>
> Subject: [Tutor] Help with strings and lists.
> To: <online330983 at telkomsa.net>, tutor at python.org
> Message-ID:
> <OFB413F236.A7BCF1CE-ONC12571AB.0036011C-C12571AB.0038186F at velux.com>
> Content-Type: text/plain; charset="iso-8859-2"
>
> Dear Alan,
>
> Probably you will be interested about list comprehension and zip(), as it
> can simplify all the similar tasks.
>
<snip>
Hi Janos,
What a sexy piece of code! Oh man, I have a lot to learn.
The code didn't justify as required, so I combined your code with
something from Kent. The code is now:
def format (value, width):
if value.isdigit():
return value.rjust(width) + ' '
else:
return value.ljust(width)
s = ('Monday 7373 3663657 2272 547757699 reached 100%',
'Tuesday 7726347 552 766463 2253 under-achieved 0%',
'Wednesday 9899898 8488947 6472 77449 reached 100%',
'Thursday 636648 553 22344 5699 under-achieved 0%',
'Friday 997 3647757 78736632 357599 over-achieved 200%')
table = [line.split() for line in s]
transposed = zip(*(table))
maxWidths = [max([len(str(cell)) for cell in column]) for column in
transposed]
print '\n'.join([' '.join([ format(field,w) for (field, w) in zip(line,
maxWidths)]) for line in table])
I noticed that if one line has less items than the rest (i.e. one less
column), that column is ignored for all lines. I'll work around that
somehow.
Thanks, I will stare in wonder at that code for years to come.
More information about the Tutor
mailing list