I've got a problem with writing algorithm. My program has input, where user should write his own today's expenses in format "Smth:Price:Smth:Price etc.". Then program have to split this elements and add to the excel file. For example to B3 and D3 cells. The problem is that I don't how to write cycle to processing user input and how can I split smth and price in order to write in different cells.
If you couldn't understand my problem, write If you have alternative algorithm that will be easy, write
Please help me, thanks.
P.S. I use openpyxl, python 3.9.7
splitting = int_spending.split(':')
x = len(splitting)
for x in splitting:
print(x)
CodePudding user response:
.Hello and welcome :)
I am not sure if I understood your question completely, but here is an working example
You receive your input like this:
your_input = "item1:45.67:item2:95.34:item3:12.98"
The first thing is to split
data = your_input.split(":")
['item1', '45.67', 'item2', '95.34', 'item3', '12.98']
Then you want to create tuples of item-price-pairs and cast the datatype of price from string to float.
as_pairs = [(data[i], float(data[i 1])) for i in range(0, len(data), 2)]
[('item1', 45.67), ('item2', 95.34), ('item3', 12.98)]
Now I open an excel file, select the first worksheet and append the data.
import openpyxl
wb = openpyxl.load_workbook("example.xlsx")
ws = wb.worksheets[0]
for elem in as_pairs:
ws.append(elem)
wb.save("example.xlsx")