gpt4 book ai didi

python - 用 Python 3 制作账单

转载 作者:行者123 更新时间:2023-12-01 09:19:19 24 4
gpt4 key购买 nike

我正在尝试编写代码来打印帐单,但由于字符长度不同而出现间距问题。在下面的代码中,我添加了长度检查,以便如果本例中索引 [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

最佳答案

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com