【问题标题】:How to change 0.9M to float number Python3?如何将 0.9M 更改为浮点数 Python?
【发布时间】:2020-05-09 15:11:58
【问题描述】:

是否有 Python3 库将字符串数字的缩写转换为:10K、0.2M、32B 等为浮点数?

例如:10K => 10000 0.9M=> 9000000 以此类推。

如果没有库,那么转换这些数字的有效方法是什么?

**我试图从字母中拆分数字,但它只适用于 int 而不是 double。

test_str = "9M"
temp = re.compile("([0-9]+)([a-zA-Z]+)")
res = temp.match(test_str).groups()

更多信息:我以这种方式从客户那里获得号码,但无法更改。后期计算需要浮动

谢谢!

【问题讨论】:

  • 在第一组允许的字符中添加点.怎么样?
  • 类似于re.sub(r'(\d*\.?\d+)([KMGT])\b', lambda x: str(int(x.group(1))*dct_num[x.group(2)]), test_str) 的东西,其中dct_num 是带有{'K': 1000, 'M': 1000000} 等的字典。

标签: python python-3.x regex numbers python-3.7


【解决方案1】:

试试

>>> import re
>>>
>>> fact_dic = {'': 1, 'K': 1000, 'M': 1000000}
>>>
>>> def GetFloatFromFactor( input ):
...     m = re.search( r"^(\d+(?:\.\d*)?|\.\d+)([KM]?)$", input)
...     if m != None:
...         fval = float( m.group(1) ) * fact_dic[ m.group(2) ]
...         return fval
...     else:
...         return "no match"
...
>>> GetFloatFromFactor( '3K' )
3000.0
>>> GetFloatFromFactor( '12.4M' )
12400000.0
>>> GetFloatFromFactor( '098.281' )
98.281

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-19
    • 2012-04-15
    • 1970-01-01
    • 2011-02-26
    • 1970-01-01
    • 2015-05-20
    • 2021-11-14
    • 2018-01-11
    相关资源
    最近更新 更多