0

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!

rmahesh
  • 739
  • 2
  • 14
  • 30

3 Answers3

1

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.

Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
1

You can use format in Python to format your strings. Also, count variable is not required in your code because you can get value directly from looping variable.

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

print("Lo: loc_pop")
print("-----------")

for x in range(0, len(population)):
    print('{}{:>10}'.format(x+1, population[x]))

# Lo: loc_pop 
# ----------- 
# 1     60000 
# 2    120000 
# 3    200000 
# 4      5000
Austin
  • 25,759
  • 4
  • 25
  • 48
0

The most simple solution is probably to use pandas.

import pandas as pd

d = {'loc_pop': [60000, 120000, 200000, 5000]}
df = pd.DataFrame(data=d)
print(df)

Result:

   loc_pop
0    60000
1   120000
2   200000
3     5000
obchardon
  • 10,614
  • 1
  • 17
  • 33