[Solved] Seperating the numbers from strings to do the maths and return the string with the results [closed]


There are a few different components to this problem. First, how do you split the receipt into each individual company. Next you need to be able to parse the company’s ID. Finally you need to be able to parse the quantity, cost, and total cost from a line item.

Splitting Receipts

Your method of splitting receipts depends on the separator. If you know that the number of hyphens is the same, you can split your input on that.

SEPARATOR = "---------------------------"

with open('input-file.txt') as f:
    contents = f.read()

# We only want to keep chunks of the file that have content.
company_receipts = []
for receipt in contents.split(SEPARATOR):
    if receipt.trim():
        company_receipts.append(receipt)

This should give you a list where each item is something like:

CompanyID: 000000000000
Pizza: 2   3.15    6.30
spaghetti:  1   7    7
ribye: 2  40  80

Parsing Company IDs

The simple assumption here would be that the first line of every receipt is the company. We can use the same split operation we used before to separate the lines of the receipt as well as the parts of the line.

text = \
"""
CompanyID: 000000000000
Pizza: 2   3.15    6.30
spaghetti:  1   7    7
ribye: 2  40  80
"""

lines = text.split('\n')
company_line = lines[0]

print(company_line.split(' '))
# Output: ['CompanyID:', '000000000000']

You can pull out the relevant parts of the line using their indices and you can convert strings to numbers with int(value).

Parsing Line Items

You can also use splits to get quantities, costs, and total costs from each line item. Using the lines variable from above:

# Remember lines also includes the company line, which we want to exclude
items = lines[1:]

for item in items:
    item_components = item.split(' ')

    # Now you can pull out the components you want
    item_name = item_components[0]         # Example: 'Pizza:'
    item_cost = item_components[1].trim()  # Example: '3.15'

Since some of these components are decimals, you can parse them with float (instead of int), although with money you may want to deal with cents instead of dollars so everything is whole numbers and there are no rounding issues.

Compose

You should be able to use the logic laid out above to compose your own logic and accomplish your goal.

solved Seperating the numbers from strings to do the maths and return the string with the results [closed]