用Python 3付账

时间:2018-06-19 14:39:36

标签: python

我正在尝试编写代码以打印钞票,但由于字符长度不同,间距存在问题。在下面的代码中,我添加了一个长度检查,以便如果产品名称(在这种情况下为index [0])具有较多的字母,则其空间将比其他字母少。但是现在索引[2]中存在一个数量问题。例如,如果我在两个列表中都输入相同数量的数量(例如2和3),则该数量有效,但是当数量以十或十为单位时,会出现间距错误。例如(2&23)

tprice = 0
tup = [['apple','100','2'],['blackberry','100','23']]
f= open(filename,'w')
g= open('recpt.txt','r')
lines = g.readlines()
for line in lines:
    base = line.split()
    tup.append(base)
print('S.no','\t','Product','\t','Unit','\t','Price')
for i in range(len(tup)):
    if len(tup[i][0]) <= 7:
      print([i+1],'\t',tup[i][0],'\t','\t',tup[i][2],'\t',tup[i][1])
    else:
        print([i+1], '\t', tup[i][0], '\t', tup[i][2],'\t',tup[i][1])
    price = int(tup[i][1])
    tprice += price
print(tprice)

我应该怎么做才能使账单相等

Here is the screenshot of error

1 个答案:

答案 0 :(得分:1)

format函数似乎很完美。像这样尝试:

tprice = 0
tup = [['apple', '100', '2'], ['blackberry', '100', '23']]
myformat = "{:<10}{:<25}{:<5}{}"

f = open(filename, 'w')
g = open('recpt.txt', 'r')
lines = g.readlines()

for line in lines:
    base = line.split()
    tup.append(base)

print(myformat.format('S.no', 'Product', 'Unit', 'Price'))

for i in range(len(tup)):
    if len(tup[i][0]) <= 7:
        print(myformat.format(str([i + 1]), tup[i][0], tup[i][2], tup[i][1]))
    else:
        print(myformat.format(str([i + 1]), tup[i][0], tup[i][2], tup[i][1]))

    price = int(tup[i][1])
    tprice += price

print(tprice)

输出:

S.no      Product                  Unit Price
[1]       apple                    2    100 
[2]       blackberry               23   100