gpt4 book ai didi

python - 将字符串解析为具有不同分隔符的 float

转载 作者:太空宇宙 更新时间:2023-11-03 14:31:55 24 4
gpt4 key购买 nike

我有许多表示数字的字符串,它们使用逗号或点来分隔千位并具有不同的 float 分隔符。例如:

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

如何在 Python 中将它们转换为 float ?

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

最佳答案

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)

关于python - 将字符串解析为具有不同分隔符的 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9227335/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com