tendaitakas
tendaitakas

Reputation: 358

Python split currency string into currency code and amount

I am trying to split R15.49 to (R, 15.49) or

ZAR15.49 to (ZAR, 15.49)

I have tried one of the solutions here and implememted the function below:

def splitCurrency(string):    
    match = re.search(r'([\D]+)([\d,]+)', string)
    output = (match.group(1), match.group(2).replace(',',''))
    return output

But I am getting (R, 15) or (ZAR, 15). and its ignoring the digits after the decimal place

Upvotes: 1

Views: 204

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521457

If you want to fish out these values from a larger text, then use re.findall:

inp = "R15.49 or ZAR15.49"
matches = re.findall(r'\b([A-Z]+)(\d+(?:\.\d+)?)\b', inp)
print(matches)

This prints:

[('R', '15.49'), ('ZAR', '15.49')]

Upvotes: 2

Related Questions