python - 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!
解决方案
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.
推荐阅读
- .net - 如何使用 dotnet 自定义模板重命名文件夹?
- r - 如何在 colnames R 中允许特殊字符(葡萄牙语)
- r - 如何更改时间序列图中的 x 轴刻度(年到月)?
- python - http.client.RemoteDisconnected:当函数调用自身时,远程结束关闭连接而没有响应
- .net-core - Redis 背板 - 大数据量的 AddStackExchangeRedis
- mysql - Xampp:数据库连接被拒绝
- r - 在 df 中给出/取回一定数量的行
- amazon-ec2 - Windows 服务器在 5 次 RDP 登录尝试失败后重新启动
- gnuplot - Gnuplot - 绘制矩阵并用数字替换正方形
- java - 在 Picocli 的单元测试中检查选项的值