如何在Python中将带点和逗号的字符串转换为浮点数


85

如何在Python中转换类似123,456.908float的字符串123456.908


9
做到这一点的正确方法是使用该locale模块-其他所有内容只是一个非常讨厌的hack,将来会给您带来麻烦。
尼克·巴斯汀

Answers:


128

只需删除,带有replace()

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

14
这取决于语言环境。法国9 988 776,65欧元,德国9.988.776,65欧元,德国9,988,776.65欧元,美国
Alexandru R

如果您要在源代码中编写常量,并且想使用逗号使其更具可读性,那么这是一种方法,而不是语言环境,这会导致代码在另一个位置失败。 python cd_size = float("737,280,000".replace(',','')) (我实际上使用过int)
hum3 '18

如果要在源代码中编写字符串文字常量,然后将其显式转换为整数或浮点数,则表明设计存在问题。但是,即使可以辩护,也可以针对该上下文将语言环境临时设置为写入代码的语言环境,然后在处理用户输入时恢复适合用户的上下文。这就是为什么首先存在的原因setlocale
Karl Knechtel

不这样做,它允许诸如“ 123 ,,, 345”之类的东西
amohr '19

148

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

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

3
到目前为止,最pythonic和直观的方式。+1
Aufwind

2
如果示例中同时包含小数点和数字分组字符,我将对此投票投票……
martineau 2011年

14
好的脚本,坏的图书馆:Extension modules should never call setlocale()
blueFast 2014年

12
@wanderer:不推荐使用atof strings内置方法。我在这里使用的是标准库模块中的函数atof,该函数locale完全不被弃用。
Karl Knechtel 2015年

5
这就是为什么星形导入效果不好的原因-我建议您编辑此locale.atof
符号

6

那这个呢?

 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 = s.replace('.','').replace(',','.')
number = float(s)

希望对你有帮助


5

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

>>> 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


2

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

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

re是完成这项任务的重要工具。
Roman Bodnarchuk 2011年

@John Doe:现在看起来好多了。我喜欢float(number)它的描述性风格。+1 ;-)
Aufwind 2011年

2
在法国的9 988 776,65欧元在德国的9.988.776,65欧元在美国的9,988,776.65欧元---->您确定它能正常工作吗?
Alexandru R


1

针对不同货币格式的更好解决方案:

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))
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.