[Tutor] Print a list in columnar format
Douglas N. Shawhan
lysdexia at crackrabbit.com
Thu Oct 7 05:23:12 CEST 2004
Using a '-' in front of a string will left-justify the string in the output.
You can change the offset by placing an integer between the '%' and the
's' in a string substitution.
Like so:
import random
for each in range(20):
print '%10s %-10s'%(random.randint(1,10000), random.randint(1,100000))
2305 59532
5211 49815
4685 72079
3752 64024
3528 21127
6577 56976
7072 29711
2106 23914
273 9873
5553 20319
9932 8607
9312 21973
6650 77566
2807 20809
8398 6245
8005 99265
6608 76452
2207 92504
236 31435
1175 24644
(if you are not viewing this message in a monospaced font it won't be as
impressive! Looks nice in the interpreter, though.
It works for more than two columns:
>>> for each in range(20):
... print '%10s %-10s %20s' %(random.randint(1,10000),
random.randint(1,100000), random.randint(1000, 100000))
...
8842 93134 43106
1313 27495 66077
9827 52848 15149
992 47592 54314
6661 71357 38458
1903 75534 87374
5183 95922 7436
4553 39353 61334
3067 84029 48230
2574 21826 52559
4239 6424 11370
2271 34964 4177
9770 90979 39463
6787 50783 98180
1679 29670 65847
6515 29142 78164
7406 76963 57462
6717 79017 66864
5467 17790 5714
4977 15100 45395
Play with it for a while! It makes sense!
More information about the Tutor
mailing list