Python - 格式化打印以对齐特定列

时间:2016-04-10 04:44:57

标签: python python-3.x formatting tuples

我正在尝试格式化print语句以对齐特定列。

目前我的输出是:

0 - Rusty Bucket (40L bucket - quite rusty) = $0.00
1 - Golf Cart (Tesla powered 250 turbo) = $195.00*
2 - Thermomix (TM-31) = $25.50*
3 - AeroPress (Great coffee maker) = $5.00
4 - Guitar (JTV-59) = $12.95

我正在寻找的输出是:

0 - Rusty Bucket (40L bucket - quite rusty)    = $0.00
1 - Golf Cart (Tesla powered 250 turbo)        = $195.00*
2 - Thermomix (TM-31)                          = $25.50*
3 - AeroPress (Great coffee maker)             = $5.00
4 - Guitar (JTV-59)                            = $12.95

以下是我目前用于打印的代码:

def list_items():
    count = 0
    print("All items on file (* indicates item is currently out):")
    for splitline in all_lines:
        in_out = splitline[3]
        dollar_sign = "= $"
        daily_price = "{0:.2f}".format(float(splitline[2]))
        if in_out == "out":
            in_out = str("*")
        else:
            in_out = str("")
        print(count, "- {} ({}) {}{}{}".format(splitline[0], splitline[1], dollar_sign, daily_price, in_out))
        count += 1

我尝试使用格式如:

print(count, "- {:>5} ({:>5}) {:>5}{}{}".format(splitline[0], splitline[1], dollar_sign, daily_price, in_out))

但是从来没有能够只让一列对齐。任何帮助或建议将不胜感激!我也在使用python 3.x

要注意我使用元组来包含所有信息,其中all_lines是主列表。该信息最初是从csv中读取的。为可怕的命名约定道歉,试图首先处理功能。

很抱歉,如果这已在其他地方得到解答;我试过看。

编辑:这是我用于all_lines的代码

import csv
open_file = open('items.csv', 'r+')
all_lines = []
for line in open_file:
    splitline = line.strip().split(',')
    all_lines.append((splitline[0], splitline[1], splitline[2], splitline[3]))

这是csv文件信息:

Rusty Bucket,40L bucket - quite rusty,0.0,in
Golf Cart,Tesla powered 250 turbo,195.0,out
Thermomix,TM-31,25.5,out
AeroPress,Great coffee maker,5.0,in
Guitar,JTV-59,12.95,in

3 个答案:

答案 0 :(得分:0)

你应该看看str.ljust(width[, fillchar])

> '(TM-31)'.ljust(15)
'(TM-31)        '  # pad to width

然后提取可变长度{} ({})部分并将其填充到必要的宽度。

答案 1 :(得分:0)

您正在寻找的可能是:

[编辑]我现在还包括一个制表版本,因为你可以获得灵活性。

import csv
from tabulate import tabulate
open_file = open('items.csv', 'r+')
all_lines = []
for line in open_file:
    splitline = line.strip().split(',')
    all_lines.append((splitline[0], splitline[1], splitline[2], splitline[3]))

#print all_lines
count = 0
new_lines=[]
for splitline in all_lines:
    in_out = splitline[3]
    dollar_sign = "= $"
    daily_price = "{0:.2f}".format(float(splitline[2]))
    if in_out == "out":
        in_out = str("*")
    else:
        in_out = str("")
    str2='('+splitline[1]+')'    
    print count, "- {:<30} {:<30} {}{:<30} {:<10}".format(splitline[0], str2, dollar_sign, daily_price, in_out)
    new_lines.append([splitline[0], str2, dollar_sign, daily_price, in_out])
    count += 1

print tabulate(new_lines, tablefmt="plain")
print
print tabulate(new_lines, tablefmt="plain", numalign="left")

答案 2 :(得分:0)

我不喜欢自己控制打印格式的想法。

在这种情况下,我会利用一个制表库,例如:Tabulate

两个关键点是:

  1. 将数据保存在表格中(例如列表中的列表)
  2. 使用tablefmt参数选择正确的打印格式。