Python在一个字符串中高效地分割货币符号和数字

2024-06-16 12:27:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类似'$200,000,000''Yan300,000,000'的字符串

我想分割货币和数字,并输出一个元组('$', '200000000'),在数字字符串中没有','。在

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

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循环。有什么建议吗?在


Tags: 字符串in脚本fordef货币数字元组
3条回答
>>> filter(str.isdigit, s)
'200000000'
>>> filter(lambda x: not x.isdigit() and x != ',', s)
'$'
>>> 
>>> (filter(lambda x: not x.isdigit() and x != ',' ,s), filter(str.isdigit, s))
('$', '200000000')
>>> 
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不以货币符号(或任何非数字)开头,则split_currency将引发一个值错误。如果愿意,可以使用try...except以不同的方式处理这种情况。在

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

(感谢张阳玉指出我没有完全回答问题)

相关问题 更多 >