Hasan Hussain
Hasan Hussain

Reputation: 9

How to align columns

I am running a model which displays a table of upto 25 generations. However as the number of rows increase, so do the numbers which makes the table look messy. This is the code - look at the link to understand what happens. image of table running

 for x in range(gen_num+1):
    print(gen_number,"\t\t",juveniles_pop,"\t\t",adults_pop,"\t\t",seniles_pop,"\t\t",juveniles_pop+adults_pop+seniles_pop)
    gen_number+=1
    seniles_pop = (seniles_pop * seniles_surv) + (adults_pop * adults_surv)
    juveniles_pop1 = adults_pop * birth_rate
    adults_pop = juveniles_pop * juveniles_surv
    juveniles_pop = juveniles_pop1

Upvotes: 0

Views: 105

Answers (2)

nanojohn
nanojohn

Reputation: 582

Look at using the str.format function to make your output alignment pretty. https://docs.python.org/2/library/string.html

In particular, here is an example of how you might want to solve your problem:

for x in range(gen_num+1):
    print('{0:{width}} {1:{width}} {2:{width}} {3:{width}} {4:{width}}'.format(gen_number,juveniles_pop,adults_pop,seniles_pop,juveniles_pop+adults_pop+seniles_pop,width=6))
    gen_number+=1
    seniles_pop = (seniles_pop * seniles_surv) + (adults_pop * adults_surv)
    juveniles_pop1 = adults_pop * birth_rate
    adults_pop = juveniles_pop * juveniles_surv
    juveniles_pop = juveniles_pop1

Upvotes: 0

cs95
cs95

Reputation: 402483

In instances like this, str.format is a good choice:

print("{:<10} {:<10} {:<10} {:<10} {:<10} {:<10} {:<10}".format(gen_number, juveniles_pop, adults_pop, seniles_pop, juveniles_pop, adults_pop, seniles_pop)

The code above will left justify your data, each number is placed in a field 10 spaces wide. You can adjust the number as per your requirement.

Here's an example:

In [517]: for _ in range(10): print("{:<10} {:<10}".format(random.randint(0, 123456), random.randint(0, 123456)))
68434      11170     
95911      46785     
96425      57497     
108395     106972    
45328      877       
97760      22434     
37254      72544     
104063     53772     
72188      116733    
20195      70798  

Upvotes: 1

Related Questions