問題描述
如何明確告訴 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 字符串顯式轉換為浮點數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!