Alignment in Python
本问题已经有最佳答案,请猛点这里访问。
我正在努力调整我的输出。我使用了制表功能。但是教授说:"这段代码不能使用制表符或空格来对齐,而是应该使用格式化的输出。"
我试着用
我不能使用str(),因为我们在课堂上还没有学到这些。我们只介绍标签、空格、左、右和中心调整
问题:我需要在继续之前将小计四舍五入到最近的一分钱,然后在继续之前将税款四舍五入到最近的一分钱。但我做到了
1 | format(Subtotal= subPot + petPri + bagPri, '.1f') |
我得到
positional argument follows keyword argument
当我尝试
1 | Tax = Subtotal * TAX_RATE, format(Subtotal, '.1f'), |
我得到:
unsupported operand type(s) for +: 'float' and 'tuple'
这是我的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | # Calculations for overall total price Subtotal = subPot + petPri + bagPri Tax = Subtotal * TAX_RATE TOTAL = Subtotal + Tax # Output print ("-----------------------------------------------") print ("Supplies and Pricing for Order", userOrder,) print () print ("Number of small pots: \t", int(smlPot),) print ("Number of medium pots: \t", int(medPot),) print ("Number of large pots: \t", int(larPot),) print () print ("Petunias:", int(totPet),"plants") print ("Potting soil:", math.ceil(totBag),"bags") print () print ("Subtotal\t""$""\t", format(Subtotal, ',.2f')) print ("Tax\t\t""$""\t", format(Tax, ',.2f')) print ("TOTAL\t\t""$""\t" , format(TOTAL, ',.2f')) print ("-----------------------------------------------") |
我想在不使用制表符或空格的情况下对齐所有内容。它应该是这样的:
1 2 3 4 5 6 7 8 9 10 11 12 13 | -------------------------------------------------- Supplies and Pricing for Order 1234 Number of small pots: 5 Number of medium pots: 6 Number of large pots: 7 Petunias: 101 plants Potting soil: 4 bags Subtotal $ 123.45 Tax $ 18.56 TOTAL $ 234.78 -------------------------------------------------- |
我假设您使用的是python 3.x。正如您所说,不能使用制表符和空格,您可以使用字符串方法。例如,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | subPotm, petPri, bagPri = 0, 0, 0 smlPot, medPot, larPot = 0, 0, 0 subPot = 0 TAX_RATE = 0 userOrder = 0 Subtotal = subPot + petPri + bagPri Tax = Subtotal * TAX_RATE TOTAL = Subtotal + Tax print ("-----------------------------------------------") print ("Supplies and Pricing for Order".ljust(30), end='') print (userOrder) print () print ("Number of small pots:".ljust(30), end='') print (smlPot) print ("Number of medium pots:".ljust(30), end='') print (medPot) |