如何保持对齐并分离此print语句中某些值的输出?

时间:2017-09-13 08:03:40

标签: python

我目前有以下代码生成如下所示的输出:

MENU = [["Hawaiian", 8.50], ["Pepperoni", 8.50], ["Veg Trio", 8.50], ["Simply Cheese", 8.50], ["Meat Lovers", 8.50], ["Ham & Cheese", 8.50], ["BBQ Italian Sausage", 8.50],
    ["Loaded Supreme", 13.50], ["Chicken Fajita", 13.50], ["Apricot Chicken", 13.50], ["Garlic Prawn", 13.50], ["Chicken Cranberry", 13.50]]

print("\nWe sell the following pizzas.")
for i, pizza in enumerate(MENU):
    print("{}: {}: ${:.2f}".format(str(i+1).zfill(2), MENU[i][0], MENU[i][1]))

输出

Output of this code

如何使所有价格都在他们自己的"列"种类和左对齐?我已经在这里发布了类似问题的答案中尝试了一些方法,但我无法达到我想要实现的目标。

我尝试过使用我在这里找到的方法,但他们所做的只是将冒号和价格之间的差距扩大到每个列的相同数量,这当然赢得了#39 ;让他们排成一行。

我只是在学习,所以任何帮助都会非常感激!

3 个答案:

答案 0 :(得分:1)

您可以查找名称最长的比萨饼,然后填写名称和价格之间较短名称的空格:

MENU = [["Hawaiian", 8.50], ["Pepperoni", 8.50], ["Veg Trio", 8.50], ["Simply Cheese", 8.50], ["Meat Lovers", 8.50], ["Ham & Cheese", 8.50], ["BBQ Italian Sausage", 8.50],
    ["Loaded Supreme", 13.50], ["Chicken Fajita", 13.50], ["Apricot Chicken", 13.50], ["Garlic Prawn", 13.50], ["Chicken Cranberry", 13.50]]

# Get a list of the lengths of the pizza names
menu_name_lengths = [len(k[0]) for k in MENU]

# Get the length of the longest name
max_length = max(menu_name_lengths)

# (max_length-len(pizza[0])) gives the number of spaces to fill in the gap
for i, pizza in enumerate(MENU):
    print("{} {}:{} ${:.2f}".format(str(i+1).zfill(2), pizza[0], " "*(max_length-len(pizza[0])), pizza[1]))

打印出来:

01 Hawaiian:            $8.50
02 Pepperoni:           $8.50
03 Veg Trio:            $8.50
04 Simply Cheese:       $8.50
05 Meat Lovers:         $8.50
06 Ham & Cheese:        $8.50
07 BBQ Italian Sausage: $8.50
08 Loaded Supreme:      $13.50
09 Chicken Fajita:      $13.50
10 Apricot Chicken:     $13.50
11 Garlic Prawn:        $13.50
12 Chicken Cranberry:   $13.50

答案 1 :(得分:0)

您可以使用str.format选择行的每个元素之间的间距,这将创建您要查找的列。 {:>15}表示告诉字符串向右显示15个空格。但是,右栏仍然没有对齐,但我正在为此制定解决方案,一旦我找到它就会编辑这个答案,但你可以在meatime中尝试这个。

MENU = [["Hawaiian", 8.50], ["Pepperoni", 8.50], ["Veg Trio", 8.50], ["Simply Cheese", 8.50], ["Meat Lovers", 8.50], ["Ham & Cheese", 8.50], ["BBQ Italian Sausage", 8.50],
    ["Loaded Supreme", 13.50], ["Chicken Fajita", 13.50], ["Apricot Chicken", 13.50], ["Garlic Prawn", 13.50], ["Chicken Cranberry", 13.50]]

print("\nWe sell the following pizzas.")
for i, pizza in enumerate(MENU):
    line = '{:>12}  {:>5}  {:>15}'.format(str(i+1).zfill(2), MENU[i][0], MENU[i][1])
    print(line)

答案 2 :(得分:0)

您可以进行一些更改以简化操作。

使用与@Igle类似的方法,找到最大长度可能是最好的方法,但使用内置填充而不是手动添加空格更清楚。

Pre Python 3.6

MENU = [["Hawaiian", 8.50],
        ["Pepperoni", 8.50],
        ["Veg Trio", 8.50],
        ["Simply Cheese", 8.50],
        ["Meat Lovers", 8.50],
        ["Ham & Cheese", 8.50],
        ["BBQ Italian Sausage", 8.50],
        ["Loaded Supreme", 13.50],
        ["Chicken Fajita", 13.50],
        ["Apricot Chicken", 13.50],
        ["Garlic Prawn", 13.50],
        ["Chicken Cranberry", 13.50]
    ]

print("\nWe sell the following pizzas.")

# Add 2 is optional but it makes the column a bit clearer.
mlen = max(len(p[0]) for p in MENU) + 2

for i, pizza in enumerate(MENU, 1): # Include the 1 to remove the +1 in the rest of the code
    print("{{:02d}}: {{:<{}}} ${{:>5.2f}}"
            .format(mlen) # Use multiple formats so that the padding is dynamic
            .format(i, pizza[0]+':', pizza[1]) # Use pizza rather than MENU[i]
    )

对于带有fstrings的Python3.6,一切都变得简单,因为你可以直接添加动态格式而不是使用两个步骤

# ... same set up as above
for i, pizza in enumerate(MENU, 1):
    print(f"{i:02d}: {pizza[0]+':':<{mlen}} ${pizza[1]:>5.2f}")