[英]Is it possible to add 2 lines of same text just different numerical value in File
I have a code which writes to file when user select a product for example the user select banana from program it will write in file 我有一个代码,当用户选择产品时会写入文件,例如,用户从程序中选择香蕉,它将写入文件
You have purchased 2 bananas for price of 200
but what if the user purchase 3 bananas more from the program. 但是如果用户从该程序中购买了3个以上的香蕉,该怎么办。 Is it possible to make this 2 to 5 and from price from 200 to 500 是否有可能使这个2到5以及从200到500的价格
You have purchased 5 bananas for price of 500
The command i am using for writing into file is 我用于写入文件的命令是
print('You have purchased',quantity,'Bananas for price of',price, file=test.txt)
You can build a template
string like that: 您可以构建如下的template
字符串:
>>> template_string = "You have purchased %s bananas for price of %s"
And then, you can fill in the variable placeholders with values later: 然后,您可以稍后在变量占位符中填充值:
>>> line_one = template_string % (2, 200)
>>> line_one
"You have purchased 2 bananas for price of 200"
>>> line_two = template_string % (5, 500)
>>> line_two
"You have purchased 5 bananas for price of 500"
Let's say you have 5 use cases, you should build the line 5 times for each case: 假设您有5个用例,则应为每种用例构建5次该行:
banana_price = 100
banana_transactions = [2, 3, 6, 7, 11]
template_string = "You have purchased %s bananas for price of %s"
with open('transactions.txt', 'w') as myfile:
for transaction in banana_transactions:
myfile.write(template_string % (transaction,
banana_price*transaction))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.