How do I parse a string to a float or int?

后端 未结 29 2770
醉话见心
醉话见心 2020-11-21 04:43

In Python, how can I parse a numeric string like \"545.2222\" to its corresponding float value, 545.2222? Or parse the string \"31\" t

相关标签:
29条回答
  • 2020-11-21 04:51

    To typecast in python use the constructor funtions of the type, passing the string (or whatever value you are trying to cast) as a parameter.

    For example:

    >>>float("23.333")
       23.333
    

    Behind the scenes, python is calling the objects __float__ method, which should return a float representation of the parameter. This is especially powerful, as you can define your own types (using classes) with a __float__ method so that it can be casted into a float using float(myobject).

    0 讨论(0)
  • 2020-11-21 04:52
    def get_int_or_float(v):
        number_as_float = float(v)
        number_as_int = int(number_as_float)
        return number_as_int if number_as_float == number_as_int else number_as_float
    
    0 讨论(0)
  • 2020-11-21 04:55

    By using int and float methods we can convert a string to integer and floats.

    s="45.8"
    print(float(s))
    
    y='67'
    print(int(y))
    
    0 讨论(0)
  • 2020-11-21 04:56

    Python method to check if a string is a float:

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

    A longer and more accurate name for this function could be: is_convertible_to_float(value)

    What is, and is not a float in Python may surprise you:

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

    You think you know what numbers are? You are not so good as you think! Not big surprise.

    Don't use this code on life-critical software!

    Catching broad exceptions this way, killing canaries and gobbling the exception creates a tiny chance that a valid float as string will return false. The float(...) line of code can failed for any of a thousand reasons that have nothing to do with the contents of the string. But if you're writing life-critical software in a duck-typing prototype language like Python, then you've got much larger problems.

    0 讨论(0)
  • 2020-11-21 04:56

    Instead of considering eval, following methods can be used to solve the problem

    if '.' in string:
        print(float(string))
    else:
        print(int(string))
    

    try-except can also be used as an alternative. Try converting string to int inside the try block. If the string would be a float value, it will throw an error which will be catched in the except block, like this

    try:
        print(int(string))
    except:
        print(float(string))
    
    0 讨论(0)
  • 2020-11-21 04:57
    float(x) if '.' in x else int(x)
    
    0 讨论(0)
提交回复
热议问题