在python 3中对齐多列 [英] Aligning multiple columns in python 3
本文介绍了在python 3中对齐多列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在python 3中格式化一组列.到目前为止,我还没有遇到太多的运气.
I am trying to format a group of columns in python 3. So far I have not had much luck.
这是我正在使用的代码.
This is the code I am using.
first_row = ['Indicator',':Min',':Max']
col_width = max(len(word) for word in first_row) +20# padding
print ("".join(word.ljust(col_width) for word in first_row))
print('----------------------------------------------------------------------------')
heart=['Heart Disease Death Rate (2007)',stateheart_min(),heartdis_min(),stateheart_max(),heartdis_max()]
motor=[ 'Motor Vehicle Death Rate (2009)',statemotor_min(),motordeath_min(),statemotor_max(),motordeath_max()]
teen=['Teen Birth Rate (2009)',stateteen_min(),teenbirth_min(),stateteen_max(),teenbirth_max()]
smoke=['Adult Smoking (2010)',statesmoke_min(),adultsmoke_min(),statesmoke_max(),adultsmoke_max()]
obese=['Adult Obesity (2010)',stateobese_min(),adultobese_min(),stateobese_max(),adultobese_max()]
heart_col_width = max(len(word) for word in heart)
motor_col_width = max(len(word) for word in motor)
teen_col_width = max(len(word) for word in teen)
smoke_col_width = max(len(word) for word in smoke)
obese_col_width = max(len(word) for word in obese)
for heart, motor, teen, smoke, obese in zip(heart, motor, teen, smoke, obese ):
print('{heart:{heart_col_width}}:{motor:{motor_col_width}} {teen:{teen_col_width}{smoke: {smoke_col_width}}{obese:{obese_col_width}'.format(heart, motor, teen, smoke, obese ))
推荐答案
不要使用制表符尝试对齐内容,而是在format语句中指定每列的实际宽度.
Instead of using tabs to try and align things, specify the actual width of each column in your format statement.
类似这样的东西:
print('{:20s} {:20s} {:20s}'.format(a,b,c))
这篇关于在python 3中对齐多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文