Python efficiently split currency sign and number in one string

前端 未结 6 884
一生所求
一生所求 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:17

    >>> import itertools
    >>> myStr = '$200,000,000'
    >>> ''.join(itertools.dropwhile(lambda c: not c.isdigit(), myStr))
    '200,000,000'
    >>> myStr = 'Yan300,000,000'
    >>> ''.join(itertools.dropwhile(lambda c: not c.isdigit(), myStr))
    '300,000,000'
    

    Similarly, you could use itertools.takewhile with the same lambda function to get the currency sign. However, this might be simpler:

    idx = itertools.dropwhile(lambda c: not c.isdigit()).next()
    sign, val = myStr[:idx], myStr[idx:]
    

提交回复
热议问题