Python efficiently split currency sign and number in one string

前端 未结 6 928
一生所求
一生所求 2021-01-16 07:04

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

I want to split the currency and number, and output a tuple (\'$\', \'200

6条回答
  •  温柔的废话
    2021-01-16 07:16

    import locale
    import re
    locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
    
    def split_currency(text):
        _, currency, num = re.split('^(\D+)', text, 1)
        num = locale.atoi(num)
        return currency, num
    print(split_currency('$200,000,000'))
    # ('$', 200000000)
    print(split_currency('Yan300,000,000'))
    # ('Yan', 300000000)
    

    split_currency will raise a ValueError if text does not start with a currency symbol (or anything that is not a digit). You could use try...except to handle that case differently if you wish.

提交回复
热议问题