如何将字符串解析为浮点数或整数?

新手上路,请多包涵
阅读 825
2 个回答
>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545

原文由 Harley Holcombe 发布,翻译遵循 CC BY-SA 4.0 许可协议

Python2 检查字符串是否为浮点数的方法:

 def is_float(value):
  if value is None:
      return False
  try:
      float(value)
      return True
  except:
      return False

对于 is_float 的 Python3 版本,请参见: Checking if a string can be converted to float in Python

这个函数的更长更准确的名称可以是: is_convertible_to_float(value)

什么是 Python 中的浮点数,什么不是浮点数可能会让您大吃一惊:

下面的单元测试是使用 python2 完成的。检查 Python3 对于哪些字符串可转换为浮点数有不同的行为。一个令人困惑的区别是现在允许使用任意数量的内部下划线: (float("1_3.4") == float(13.4)) 是 True

 val                   is_float(val) Note
--------------------  ----------   --------------------------------
""                    False        Blank string
"127"                 True         Passed string
True                  True         Pure sweet Truth
"True"                False        Vile contemptible lie
False                 True         So false it becomes true
"123.456"             True         Decimal
"      -127    "      True         Spaces trimmed
"\t\n12\r\n"          True         whitespace ignored
"NaN"                 True         Not a number
"NaNanananaBATMAN"    False        I am Batman
"-iNF"                True         Negative infinity
"123.E4"              True         Exponential notation
".1"                  True         mantissa only
"1_2_3.4"             False        Underscores not allowed
"12 34"               False        Spaces not allowed on interior
"1,234"               False        Commas gtfo
u'\x30'               True         Unicode is fine.
"NULL"                False        Null is not special
0x3fade               True         Hexadecimal
"6e7777777777777"     True         Shrunk to infinity
"1.797693e+308"       True         This is max value
"infinity"            True         Same as inf
"infinityandBEYOND"   False        Extra characters wreck it
"12.34.56"            False        Only one dot allowed
u'四'                 False        Japanese '4' is not a float.
"#56"                 False        Pound sign
"56%"                 False        Percent of what?
"0E0"                 True         Exponential, move dot 0 places
0**0                  True         0___0  Exponentiation
"-5e-5"               True         Raise to a negative number
"+1e1"                True         Plus is OK with exponent
"+1e1^5"              False        Fancy exponent not interpreted
"+1e1.3"              False        No decimals in exponent
"-+1"                 False        Make up your mind
"(1)"                 False        Parenthesis is bad

你认为你知道什么是数字?你没有你想的那么好!没什么大惊喜。

不要在生命攸关的软件上使用此代码!

以这种方式捕获广泛的异常,杀死金丝雀并吞噬异常会产生一个很小的机会,即有效的 float 作为字符串将返回 false。 float(...) 代码行可能由于与字符串内容无关的一千个原因中的任何一个而失败。但是,如果您正在使用像 Python 这样的鸭子类型原型语言编写对生命至关重要的软件,那么您就会遇到更大的问题。

原文由 Eric Leschinski 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题