如何格式化列表中的多个项目?

时间:2019-09-28 22:52:24

标签: python-3.x

我不知道如何格式化多个项目而不会出现错误。 我研究了新旧的格式化方法。

我尝试了("0:%d 1:%s @ $%.2f ea $%.2f).format并使用%而不是.format, 这看似简单,但我很困惑。

#how to format each item separately?
print((item['number'], item['name'], (item['price']), item_total))


#this code works
print("Grand total:" + str("${:,.2f}".format(grand_total)))

结果:

(1, 'itemName', 5.00, 5.00)
Grand total:$5.00

所需结果:

1 itemName @ $5.00 ea $5.00   #not working
Grand total: $5.00            #success
grocery_item = {}
grocery_history = []

stop = False
while not stop:
    item_name = input("Item name:\n")
    quantity = input("Quantity purchased:\n")
    cost = input("Price per item:\n")
    grocery_item = {'name': item_name, 'number': int(quantity), 'price': float(cost)}
    grocery_history.append(grocery_item)
    response = input("Would you like to enter another item?\nType 'c' for continue or 'q' to quit:\n")

    if response == 'q':
        stop = True

    grand_total = 0

for item in grocery_history:
    item_total = item['number'] * item['price']
    grand_total += item_total

    print((item['number'], item['name'], (item['price']), item_total))
    print("Grand total:" + str("${:,.2f}".format(grand_total)))

1 个答案:

答案 0 :(得分:1)

您知道如何从第二张纸上打印出来。

item = {'number': 1, 'name' : 'itemName', 'price': 5.00}
item_total = 5.00

print('{} {} @ ${:,.2f} ea ${:,.2f}'.format(item['number'], item['name'], item['price'], item_total))
print('%d %s @ $%.2f ea $%.2f' % (item['number'], item['name'], item['price'], item_total))
print(f"{item['number']} { item['name']} @ ${item['price']:,.2f} ea ${item_total:,.2f}")

对于第一条打印语句,您什么也不做。只需打印dict和variable的值即可。所有三个(带有评论的一个)给出的结果相同。

1 itemName @ $5.00 ea $5.00
1 itemName @ $5.00 ea $5.00
1 itemName @ $5.00 ea $5.00