問(wèn)題描述
如何明確告訴 python 使用點(diǎn)或逗號(hào)作為小數(shù)分隔符讀取十進(jìn)制數(shù)?我不知道將運(yùn)行我的腳本的 PC 的本地化設(shè)置,這應(yīng)該不會(huì)影響我的應(yīng)用程序,我只想說(shuō):
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")
我認(rèn)為寫作
def read_float_with_comma(num):
return float(num.replace(",", ".")
不安全,因?yàn)槲也恢绤^(qū)域設(shè)置!
is not secure, because I don't know the locale settings!
推薦答案
因?yàn)槲也恢绤^(qū)域設(shè)置
because I don't know the locale settings
您可以使用 locale
模塊進(jìn)行查找一個(gè)>:
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)
更好的是,同一個(gè)模塊為您提供了一個(gè)轉(zhuǎn)換功能,稱為 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)
這篇關(guān)于使用逗號(hào)或點(diǎn)作為分隔符將 Python 字符串顯式轉(zhuǎn)換為浮點(diǎn)數(shù)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!