我有许多字符串表示使用逗号或点来分隔数千且具有不同浮动分隔符的数字。例如:
“22 000,76”,“22.000,76”,“22,000.76”,“1022000,76”,“ - 1,022,000.76”,“1022000”,“22 000,76 $”,“$ 22 000,76”< / p>
如何在Python中将这些转换为浮点数?
在PHP中,我使用这样的函数:http://docs.php.net/manual/sr/function.floatval.php#84793
答案 0 :(得分: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)
答案 1 :(得分:0)
假设您最多有2位小数:
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