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

后端 未结 29 2774
醉话见心
醉话见心 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 05:04

    Handles hex, octal, binary, decimal, and float

    This solution will handle all of the string conventions for numbers (all that I know about).

    def to_number(n):
        ''' Convert any number representation to a number 
        This covers: float, decimal, hex, and octal numbers.
        '''
    
        try:
            return int(str(n), 0)
        except:
            try:
                # python 3 doesn't accept "010" as a valid octal.  You must use the
                # '0o' prefix
                return int('0o' + n, 0)
            except:
                return float(n)
    

    This test case output illustrates what I'm talking about.

    ======================== CAPTURED OUTPUT =========================
    to_number(3735928559)   = 3735928559 == 3735928559
    to_number("0xFEEDFACE") = 4277009102 == 4277009102
    to_number("0x0")        =          0 ==          0
    to_number(100)          =        100 ==        100
    to_number("42")         =         42 ==         42
    to_number(8)            =          8 ==          8
    to_number("0o20")       =         16 ==         16
    to_number("020")        =         16 ==         16
    to_number(3.14)         =       3.14 ==       3.14
    to_number("2.72")       =       2.72 ==       2.72
    to_number("1e3")        =     1000.0 ==       1000
    to_number(0.001)        =      0.001 ==      0.001
    to_number("0xA")        =         10 ==         10
    to_number("012")        =         10 ==         10
    to_number("0o12")       =         10 ==         10
    to_number("0b01010")    =         10 ==         10
    to_number("10")         =         10 ==         10
    to_number("10.0")       =       10.0 ==         10
    to_number("1e1")        =       10.0 ==         10
    

    Here is the test:

    class test_to_number(unittest.TestCase):
    
        def test_hex(self):
            # All of the following should be converted to an integer
            #
            values = [
    
                     #          HEX
                     # ----------------------
                     # Input     |   Expected
                     # ----------------------
                    (0xDEADBEEF  , 3735928559), # Hex
                    ("0xFEEDFACE", 4277009102), # Hex
                    ("0x0"       ,          0), # Hex
    
                     #        Decimals
                     # ----------------------
                     # Input     |   Expected
                     # ----------------------
                    (100         ,        100), # Decimal
                    ("42"        ,         42), # Decimal
                ]
    
    
    
            values += [
                     #        Octals
                     # ----------------------
                     # Input     |   Expected
                     # ----------------------
                    (0o10        ,          8), # Octal
                    ("0o20"      ,         16), # Octal
                    ("020"       ,         16), # Octal
                ]
    
    
            values += [
                     #        Floats
                     # ----------------------
                     # Input     |   Expected
                     # ----------------------
                    (3.14        ,       3.14), # Float
                    ("2.72"      ,       2.72), # Float
                    ("1e3"       ,       1000), # Float
                    (1e-3        ,      0.001), # Float
                ]
    
            values += [
                     #        All ints
                     # ----------------------
                     # Input     |   Expected
                     # ----------------------
                    ("0xA"       ,         10), 
                    ("012"       ,         10), 
                    ("0o12"      ,         10), 
                    ("0b01010"   ,         10), 
                    ("10"        ,         10), 
                    ("10.0"      ,         10), 
                    ("1e1"       ,         10), 
                ]
    
            for _input, expected in values:
                value = to_number(_input)
    
                if isinstance(_input, str):
                    cmd = 'to_number("{}")'.format(_input)
                else:
                    cmd = 'to_number({})'.format(_input)
    
                print("{:23} = {:10} == {:10}".format(cmd, value, expected))
                self.assertEqual(value, expected)
    

提交回复
热议问题