【问题标题】:How can I convert a string with dot and comma into a float in Python如何在 Python 中将带点和逗号的字符串转换为浮点数
【发布时间】:2011-10-01 18:56:15
【问题描述】:

如何在 Python 中将 123,456.908 之类的字符串转换为浮点 123456.908

【问题讨论】:

  • 正确的做法是使用 locale 模块 - 其他一切都只是一个非常讨厌的黑客,将来会给你带来麻烦。
  • 正确的localeway 也是一个很好的方法,如果你打算在多个操作系统(如 Windows 和 Linux 的风格)上使用你的程序,它们有不同的语言环境格式,甚至可能需要您安装支持所选格式的语言环境...

标签: python type-conversion


【解决方案1】:

... 或者,我们可以将整个字符串视为浮点的本地化格式,并使用本地化服务,而不是将逗号视为要过滤掉的垃圾:

from locale import atof, setlocale, LC_NUMERIC
setlocale(LC_NUMERIC, '') # set to your default locale; for me this is
# 'English_Canada.1252'. Or you could explicitly specify a locale in which floats
# are formatted the way that you describe, if that's not how your locale works :)
atof('123,456') # 123456.0
# To demonstrate, let's explicitly try a locale in which the comma is a
# decimal point:
setlocale(LC_NUMERIC, 'French_Canada.1252')
atof('123,456') # 123.456

【讨论】:

  • 迄今为止最pythonic和最直观的方式。 +1
  • 如果示例中同时包含小数点和数字分组字符,我会投票赞成这个答案...
  • 适合脚本,不适合库:Extension modules should never call setlocale()
  • @wanderer:不推荐使用的是atof 字符串的内置方法。我在这里使用的是来自locale 标准库模块的函数atof,它根本没有被弃用。
  • 这就是星号导入不好的原因 - 我建议您编辑它以导入所需的或更好的命名空间,如locale.atof
【解决方案2】:

只需删除 ,replace()

float("123,456.908".replace(',',''))

【讨论】:

  • 这取决于语言环境。法国 9 988 776,65 欧元 德国 9.988.776,65 欧元 美国 9,988,776.65 美元
  • 如果您在源代码中编写常量并希望使用逗号使其更具可读性,那么这是要走的路,而不是语言环境,这会使代码在另一个位置失败。 python cd_size = float("737,280,000".replace(',',''))(其实我用的是int)
  • 如果您在源代码中编写字符串常量,然后显式将其转换为整数或浮点数,则表明设计有问题。但即使它可以被保护 - 只是暂时将语言环境设置为编写代码的那个上下文,然后在处理用户输入时恢复适合用户的上下文。这就是为什么首先有setlocale
  • 不要这样做,它允许像“123,,,,345”这样的东西
  • 这个极其危险的替代品将fail in half of the world,另一半是中国。还有美国。欧洲、非洲、俄罗斯、南美,使用,作为小数分隔符
【解决方案3】:

如果您不知道语言环境并且想要解析任何类型的数字,请使用this parseNumber(text) function。它并不完美,但考虑到大多数情况:

>>> parseNumber("a 125,00 €")
125
>>> parseNumber("100.000,000")
100000
>>> parseNumber("100 000,000")
100000
>>> parseNumber("100,000,000")
100000000
>>> parseNumber("100 000 000")
100000000
>>> parseNumber("100.001 001")
100.001
>>> parseNumber("$.3")
0.3
>>> parseNumber(".003")
0.003
>>> parseNumber(".003 55")
0.003
>>> parseNumber("3 005")
3005
>>> parseNumber("1.190,00 €")
1190
>>> parseNumber("1190,00 €")
1190
>>> parseNumber("1,190.00 €")
1190
>>> parseNumber("$1190.00")
1190
>>> parseNumber("$1 190.99")
1190.99
>>> parseNumber("1 000 000.3")
1000000.3
>>> parseNumber("1 0002,1.2")
10002.1
>>> parseNumber("")

>>> parseNumber(None)

>>> parseNumber(1)
1
>>> parseNumber(1.1)
1.1
>>> parseNumber("rrr1,.2o")
1
>>> parseNumber("rrr ,.o")

>>> parseNumber("rrr1rrr")
1

【讨论】:

    【解决方案4】:

    如果你有一个逗号作为小数分隔符和点作为千位分隔符,你可以这样做:

    s = s.replace('.','').replace(',','.')
    number = float(s)
    

    希望对你有帮助

    【讨论】:

      【解决方案5】:

      这个怎么样?

       my_string = "123,456.908"
       commas_removed = my_string.replace(',', '') # remove comma separation
       my_float = float(commas_removed) # turn from string to float.
      

      简而言之:

      my_float = float(my_string.replace(',', ''))
      

      【讨论】:

        【解决方案6】:
        s =  "123,456.908"
        print float(s.replace(',', ''))
        

        【讨论】:

        • 重复答案。
        【解决方案7】:

        这是我为您编写的一个简单方法。 :)

        >>> number = '123,456,789.908'.replace(',', '') # '123456789.908'
        >>> float(number)
        123456789.908
        

        【讨论】:

        • re 是完成此类任务的大锤。
        • @John Doe:现在看起来好多了。我喜欢float(number),因为它具有描述性。 +1 ;-)
        • 9 988 776,65 € 在法国 德国 9.988.776,65 € 在美国 $9,988,776.65 ----> 你确定它有效吗?
        【解决方案8】:

        different currency formats 的更好解决方案:

        def text_currency_to_float(text):
          t = text
          dot_pos = t.rfind('.')
          comma_pos = t.rfind(',')
          if comma_pos > dot_pos:
            t = t.replace(".", "")
            t = t.replace(",", ".")
          else:
            t = t.replace(",", "")
        
          return(float(t))
        

        【讨论】:

          【解决方案9】:

          只需用 replace() 替换,

          f = float("123,456.908".replace(',','')) print(type(f))

          type() 将显示它已转换为浮点数

          【讨论】:

          • 这些都是很好的答案。正如我所做的 `df = pd.read_csv(filename, thousands=',') 它已经解决了所有潜在列的读取问题。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-04-19
          • 1970-01-01
          • 2020-04-21
          相关资源
          最近更新 更多