用不同分隔符将字符串解析为浮点数

3 投票
2 回答
1547 浏览
提问于 2025-04-17 12:45

我有一些字符串,它们表示数字,这些数字用逗号或点来分隔千位数,并且小数点的表示方式也不一样。例如:

"22 000,76", "22.000,76", "22,000.76", "1022000,76", "-1,022,000.76", "1022000", "22 000,76$", "$22 000,76"

我该如何在Python中把这些字符串转换成浮点数呢?

在PHP中,我会使用这样的函数:http://docs.php.net/manual/sr/function.floatval.php#84793

2 个回答

0

假设你最多只能有两位小数:

sign_trans = str.maketrans({'$': '', ' ':''})
dot_trans = str.maketrans({'.': '', ',': ''})

def convert(num, sign_trans=sign_trans, dot_trans=dot_trans):
    num = num.translate(sign_trans)
    num = num[:-3].translate(dot_trans) + num[-3:]
    return float(num.replace(',', '.'))

我在你的例子上进行了测试:

>>> for n in nums:
...     print(convert(n))
...
22000.76
22000.76
22000.76
1022000.76
-1022000.76
1022000.0
22000.76
22000.76
5

在编程中,有时候我们会遇到一些问题,特别是在使用某些工具或库的时候。这些问题可能会让我们感到困惑,尤其是当我们刚开始学习编程的时候。

比如说,有人可能在使用某个特定的功能时,发现它没有按照预期工作。这时候,我们就需要去查找原因,看看是不是有什么地方没有设置好,或者是不是有其他的因素影响了它的运行。

在这种情况下,查看相关的文档或者在网上搜索类似的问题,通常能帮助我们找到解决方案。很多时候,其他人也遇到过类似的问题,他们的经验和解决方法可以给我们提供很大的帮助。

总之,遇到问题时不要着急,慢慢查找资料,理解每一步,最终你会找到解决办法的。

import re
import locale

# Remove anything not a digit, comma or period
no_cruft = re.sub(r'[^\d,.-]', '', st)

# Split the result into parts consisting purely of digits
parts = re.split(r'[,.]', no_cruft)

# ...and sew them back together
if len(parts) == 1:
    # No delimeters found
    float_str = parts[0]
elif len(parts[-1]) != 2:
    # >= 1 delimeters found. If the length of last part is not equal to 2, assume it is not a decimal part
    float_str = ''.join(parts)
else:
    float_str = '%s%s%s' % (''.join(parts[0:-1]),
                            locale.localeconv()['decimal_point'],
                            parts[-1])

# Convert to float
my_float = float(float_str)

撰写回答