如何在Python中将字符串解析为float或int?

在Python中,我怎样才能解析一个数字字符串像"545.2222"到它相应的浮点值542.2222 ? 或者将字符串"31"解析为一个整数31

我只想知道如何将一个浮点string解析为一个float ,然后(单独)将一个int string解析为一个int


>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545

def num(s):
    try:
        return int(s)
    except ValueError:
        return float(s)

检查字符串是否为float的Python方法:

def isfloat(value):
  try:
    float(value)
    return True
  except:
    return False

该函数的名称越长越准确: isConvertibleToFloat(value)

什么是,而不是Python中的float可能会让你感到惊讶:

val                   isfloat(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
"tn12rn"          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,234"               False        Commas gtfo
u'x30'               True         Unicode is fine.
"NULL"                False        Null is not special
0x3fade               True         Hexidecimal
"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

你以为你知道什么是数字? 你不如你想象的那么好! 不是很大的惊喜。

链接地址: http://www.djcxy.com/p/1321.html

上一篇: How do I parse a string to a float or int in Python?

下一篇: Prettify JSON Array in JavaScript