问题描述
如何显式地告诉python使用点或逗号作为小数点分隔符来读取十进制数字?我不知道将运行我的脚本的个人电脑的本地化设置,这不应该影响我的应用程序,我只想说:
$ b $
f = read_float_with_point(3.14)
或
f = read_float_with_comma(3,14)
我认为写作
$ $ $ $ $ $ $ $ $ $ $ $ def $ read_float_with_comma($)
return float(num.replace (,,。)
不安全,因为我不知道区域设置设置!
您可以使用: > locale.nl_langinfo(locale.RADIXCHAR)
'。'
或
>& > locale.localeconv()['decimal_point']
'。'
使用它,你的代码可能会变成:
$ b $ pre $ import locale
_locale_radix = locale.localeconv()['decimal_point']
$ b $ def read_float_with_comma(num):
if _locale_radix!='。':
num = num.replace(_locale_radix,。)
return float(num )
更好的是,同一个模块有一个转换函数,叫做: p>
导入区域设置
def read_float_with_comma(num):
返回locale.atof(num)
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")
or
f = read_float_with_comma("3,14")
I think that writing
def read_float_with_comma(num):
return float(num.replace(",", ".")
is not secure, because I don't know the locale settings!
You could look that up using the locale
module:
>>> locale.nl_langinfo(locale.RADIXCHAR)
'.'
or
>>> 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)
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字符串明确地使用逗号或点作为分隔符转换为浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!