首页 > 解决方案 > Python将货币字符串拆分为货币代码和金额

问题描述

我正在尝试拆分R15.49 to (R, 15.49)

ZAR15.49 to (ZAR, 15.49)

我在这里尝试了一种解决方案并实现了以下功能:

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

但我得到(R,15)或(ZAR,15)。并且忽略小数点后的数字

标签: python-3.xstringalgorithm

解决方案


如果您想从较大的文本中找出这些值,请使用re.findall

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

这打印:

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

推荐阅读