简体   繁体   中英

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

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')]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM