I am reformatting a large set of sales data.
Each sale shows the name of the item, number of items being sold, and the price rounded to the nearest whole number.
1 bag of 20 Apples sold for $3:
Apple/,20,3,
If more than one sale occurs, the sales data replaces the item name for every result after the first one.
4 bags of 20 Apples sold for $3: Apple/,20,3%20,3%20,3%20,3,
I need to display the item name for every sale instead of the % sign
Desired Result: Apple/,20,3,Apple/,20,3,Apple/,20,3,Apple/,20,3,
So Far: I have been banging my head against this for six hours, and tried several approaches.
I had thought running a regex substitution using the re module in python using the expression ([A-Za-z]+\/)?(\%)?(\d+\,\d+\,)
would produce the needed result after substituting \1\3 for the full match, however this only applies the first capture group to the beginning of all consecutive matches of the third capture group.
Apple/,20,3,20,3,20,3,20,3,
I suspect this has to do with the difference between capture groups and capture objects, but am stuck trying to find a way to append the first capture group to each appearance of a capture object for a given capture group (eg, append capture group 1 to the beginning of every match for capture group 3.)
To get around this, I tried a modified version of the answer for: https://stackoverflow.com/questions/32670413/replace-all-matches-using-re-findall
import re
regex = re.compile('([A-Za-z]+\/)?(\%)?(\d+\,\d+\,)', re.S)
itemsales = 'Apple/20,3,%20,3,%20,3,%20,3,'
sales_fixed = regex.sub(lambda m: m.group().replace('%',"\1",1), myfile)
print(sales_fixed)
and this returns the exact same result of
Apple/,20,3,20,3,20,3,20,3,
which I suspect may be a result of incorrectly referencing my capture group in the substitution
How can I replace the percent signs with the product name?