繁体   English   中英

关于 python 3 中格式化的问题

[英]Questions about formatting in python 3

对于我们的 python class,我们需要使格式与给出的示例完美匹配。 该示例如下所示:

   Average       Gallons       Cost Per   
    Speed          Used         Gallon    
    65.62         72.41          2.07     

我的 output 看起来像这样:

Average       Gallons       Cost Per      
Speed         Used          Gallon        
65.62         72.41          2.07          

我需要知道如何将我的 output 格式化为示例中给出的格式。 帮助将不胜感激。 这是我的代码:

driven = 1050
mpg = 14.5
money = input("How much money was spent: ")
hours = input("Hours driven: ")
average = driven / hours
num = driven / mpg
cpg = money / num
print("{:<14}{:<14}{:<14}".format("Average", "Gallons", "Cost Per"))
print("{:<14}{:<14}{:<14}".format("Speed", "Used", "Gallon"))
print("{:<14.2f}{:<14.2f} {:<14.2f}".format(average, num, cpg))

提前致谢!

使用^而不是<应该可以解决问题:

driven = 1050
mpg = 14.5
money = int(input("How much money was spent: "))
hours = int(input("Hours driven: "))
average = driven / hours
num = driven / mpg
cpg = money / num
print("{:^14}{:^14}{:^14}".format("Average", "Gallons", "Cost Per"))
print("{:^14}{:^14}{:^14}".format("Speed", "Used", "Gallon"))
print("{:^14.2f}{:^14.2f} {:^14.2f}".format(average, num, cpg))

Output:

   Average       Gallons       Cost Per    
    Speed          Used         Gallon     
    52.50         72.41          27.62     

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM