【发布时间】:2018-09-08 00:09:13
【问题描述】:
我有一个代码询问订购果汁和苹果酒的人数,并据此计算总数、小计、平均值等。我的格式有问题,如标题下方(例如:姓名、苹果酒、小计),这些数字没有正确反映在相应的标题下。如何在python中格式化
How many people ordered? 2
Enter the name of Person #1: Richard
How many orders of cider did Richard have? 13
How many orders of juice did Richard have? 9
Enter the name of Person #2: George
How many orders of cider did George have? 7
How many orders of juice did George have? 21
Names Cider Juice Subtotal (Cider) Subtotal (Juice) Total
--------------------------------------------------------------------------------
Richard 13 9 $ 71.50 $ 40.50 $ 112.00
George 7 21 $ 38.50 $ 94.50 $ 133.00
--------------------------------------------------------------------------------
Total 20 30 $ 231.00 $ 261.00 $ 492.00
Average 10.50 14.50 $ 57.75 $ 65.25 $ 123.00
代码:
print("This program calculates the prices of the orders")
person=int(input("How many people ordered?"))
person_names=[]
cider_order=[]
juice_order=[]
cider__subtotal_orders=[]
juice__subtotal_orders=[]
total_orders=[]
for a in range(person):
personnames=input("Enter the name of Person #%d:"%(a+1))
person_names.append(personnames)
cider=int(input("How many orders of cider did %s have?"%personnames))
cider_order.append(cider)
juice=int(input("How many orders of juice did %s have?"%personnames))
juice_order.append(juice)
cider__subtotal_orders.append(cider*5.50)
juice__subtotal_orders.append(juice*4.50)
total_orders.append(cider__subtotal_orders[a]+juice__subtotal_orders[a])
print("\n\n")
print("Name Cider Juice Subtotal (Cider) Subtotal (Juice) Total")
print("-------------------------------------------------------------")
for a in range(person):
print(person_names[a],cider_order[a],juice_order[a],"$",cider__subtotal_orders[a],"$",juice__subtotal_orders[a],"$",total_orders[a])
print("-------------------------------------------------------------")
print("total",sum(cider_order),sum(juice_order),"$",sum(cider__subtotal_orders),"$",sum(juice__subtotal_orders),"$",sum(total_orders))
print("Average",sum(cider_order)/person,sum(juice_order)/person,"$",sum(cider__subtotal_orders)/person,"$",sum(juice__subtotal_orders)/person,"$",
sum(total_orders)/person)
【问题讨论】:
-
print('{:^24s}'.format("MyString"))取自stackoverflow.com/questions/44781484/… -
像换行符
\n一样,您可以使用\t在字符串中插入制表符。
标签: python