简体   繁体   English

Python 将货币字符串拆分为货币代码和金额

[英]Python split currency string into currency code and amount

I am trying to split R15.49 to (R, 15.49) or我正在尝试将R15.49 to (R, 15.49)

ZAR15.49 to (ZAR, 15.49)

I have tried one of the solutions here and implememted the function below:我在这里尝试了一种解决方案,并在下面实现了 function:

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).但我得到(R,15)或(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 :如果您想从较大的文本中找出这些值,请使用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')]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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