首页 > 解决方案 > Unable to Right aligning elements print statement in loop

问题描述

So I have the following lists:

population = [60000, 120000, 200000, 5000]

Want to format the output as such:

Lo: loc_pop
-----------
1     60000
2    120000
3    200000
4      5000

The issue that I am having is that I am unable to right align the print statement so that all the values of population (regardless of size) align in the manner I displayed above.

Here is the code:

population = [123100, 60000, 98300, 220000, 5000]

print("Lo: loc_pop")
print("-----------")
count = 0
for x in range(0, len(population)):
    print(count, ":", " ", population[x])
    count = count + 1

Here is the output:

Lo: loc_pop
-----------
0 :   123100
1 :   60000
2 :   98300
3 :   220000
4 :   5000

The output seems to add a space after the "count" and before the ":", and depending on the number of digits, it is not properly right aligned.

Any help would be great!

标签: python

解决方案


If you just want to print in the specify format, this is enough, using rjust:

population = [60000, 120000, 200000, 5000]
header = "Lo: loc_pop"
header_length = len(header)

print(header)
print("-" * header_length)
for i, p in enumerate(population, 1):
    print(i, str(p).rjust(header_length - (len(str(i)) + 1)))

Output

Lo: loc_pop
-----------
1     60000
2    120000
3    200000
4      5000

However if you are planning on doing additional stuff, related to data, I suggest you take a look at pandas.


推荐阅读