Python有效地将货币符号和数字拆分为一个字符串 [英] Python efficiently split currency sign and number in one string

查看:190
本文介绍了Python有效地将货币符号和数字拆分为一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,例如'$ 200,000,000''Yan300,000,000'

I have a string like '$200,000,000' or 'Yan300,000,000'

我想拆分货币和数字,并输出一个元组('$','200000000'),数字字符串中不包含','.

I want to split the currency and number, and output a tuple ('$', '200000000'), without ',' in the number string.

当前我正在使用以下脚本,该脚本正在运行:

Currently I'm using the following script, which is working:

def splitCurrency(cur_str):
    cuttingIdx = 0
    for char in cur_str:
        try:
            int(char)
            break
        except ValueError:
            cuttingIdx = cuttingIdx + 1
    return (cur_str[0:cuttingIdx].strip(),
            cur_str[cuttingIdx:len(cur_str)].replace(',',''))

除性能和可读性外,我要避免使用for循环和try-try.有什么建议吗?

I want to avoid using for-loop and try-except for performance and readability. Any suggestions?

推荐答案

>>> import re
>>> string = 'YAN300,000,000'
>>> match = re.search(r'([\D]+)([\d,]+)', string)
>>> output = (match.group(1), match.group(2).replace(',',''))
>>> output
('YAN', '300000000')

(感谢zhangyangyu指出我没有完全回答问题)

(Thanks to zhangyangyu for pointing out I hadn't fully answered the question)

这篇关于Python有效地将货币符号和数字拆分为一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆