使用逗号或点作为分隔符将 Python 字符串显式转换为浮点数

Convert Python strings into floats explicitly using the comma or the point as separators(使用逗号或点作为分隔符将 Python 字符串显式转换为浮点数)
本文介绍了使用逗号或点作为分隔符将 Python 字符串显式转换为浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

如何明确告诉 python 使用点或逗号作为小数分隔符读取十进制数?我不知道将运行我的脚本的 PC 的本地化设置,这应该不会影响我的应用程序,我只想说:

How can I explicitly tell python to read a decimal number using the point or the comma as a decimal separator? I don't know the localization settings of the PC that will run my script, and this should not influence my application, I only want to say:

f = read_float_with_point("3.14")

f = read_float_with_comma("3,14")

我认为写作

def read_float_with_comma(num):
    return float(num.replace(",", ".")

不安全,因为我不知道区域设置!

is not secure, because I don't know the locale settings!

推荐答案

因为我不知道区域设置

because I don't know the locale settings

您可以使用 locale 模块进行查找一个>:

You could look that up using the locale module:

>>> locale.nl_langinfo(locale.RADIXCHAR)
'.'

>>> locale.localeconv()['decimal_point']
'.'

使用它,您的代码可以变成:

Using that, your code could become:

import locale
_locale_radix = locale.localeconv()['decimal_point']

def read_float_with_comma(num):
    if _locale_radix != '.':
        num = num.replace(_locale_radix, ".")
    return float(num)

更好的是,同一个模块为您提供了一个转换功能,称为 atof():

Better still, the same module has a conversion function for you, called atof():

import locale

def read_float_with_comma(num):
    return locale.atof(num)

这篇关于使用逗号或点作为分隔符将 Python 字符串显式转换为浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

patching a class yields quot;AttributeError: Mock object has no attributequot; when accessing instance attributes(修补类会产生“AttributeError:Mock object has no attribute;访问实例属性时)
How to mock lt;ModelClassgt;.query.filter_by() in Flask-SqlAlchemy(如何在 Flask-SqlAlchemy 中模拟 lt;ModelClassgt;.query.filter_by())
FTPLIB error socket.gaierror: [Errno 8] nodename nor servname provided, or not known(FTPLIB 错误 socket.gaierror: [Errno 8] nodename nor servname provided, or not known)
Weird numpy.sum behavior when adding zeros(添加零时奇怪的 numpy.sum 行为)
Why does the #39;int#39; object is not callable error occur when using the sum() function?(为什么在使用 sum() 函数时会出现 int object is not callable 错误?)
How to sum in pandas by unique index in several columns?(如何通过几列中的唯一索引对 pandas 求和?)