我正在尝试编写代码以打印账单,但由于字符长度不同,间距存在问题。在下面的代码中,我添加了一个长度检查,以便如果产品名称(在这种情况下为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)
我应该怎么做才能使账单相等
最佳答案
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
关于python - 用Python 3付账,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50931098/