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

后端 未结 29 2518
醉话见心
醉话见心 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:44

    You need to take into account rounding to do this properly.

    I.e. int(5.1) => 5 int(5.6) => 5 -- wrong, should be 6 so we do int(5.6 + 0.5) => 6

    def convert(n):
        try:
            return int(n)
        except ValueError:
            return float(n + 0.5)
    
    0 讨论(0)
  • 2020-11-21 04:45

    Users codelogic and harley are correct, but keep in mind if you know the string is an integer (for example, 545) you can call int("545") without first casting to float.

    If your strings are in a list, you could use the map function as well.

    >>> x = ["545.0", "545.6", "999.2"]
    >>> map(float, x)
    [545.0, 545.60000000000002, 999.20000000000005]
    >>>
    

    It is only good if they're all the same type.

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

    In Python, how can I parse a numeric string like "545.2222" to its corresponding float value, 542.2222? Or parse the string "31" to an integer, 31? I just want to know how to parse a float string to a float, and (separately) an int string to an int.

    It's good that you ask to do these separately. If you're mixing them, you may be setting yourself up for problems later. The simple answer is:

    "545.2222" to float:

    >>> float("545.2222")
    545.2222
    

    "31" to an integer:

    >>> int("31")
    31
    

    Other conversions, ints to and from strings and literals:

    Conversions from various bases, and you should know the base in advance (10 is the default). Note you can prefix them with what Python expects for its literals (see below) or remove the prefix:

    >>> int("0b11111", 2)
    31
    >>> int("11111", 2)
    31
    >>> int('0o37', 8)
    31
    >>> int('37', 8)
    31
    >>> int('0x1f', 16)
    31
    >>> int('1f', 16)
    31
    

    If you don't know the base in advance, but you do know they will have the correct prefix, Python can infer this for you if you pass 0 as the base:

    >>> int("0b11111", 0)
    31
    >>> int('0o37', 0)
    31
    >>> int('0x1f', 0)
    31
    

    Non-Decimal (i.e. Integer) Literals from other Bases

    If your motivation is to have your own code clearly represent hard-coded specific values, however, you may not need to convert from the bases - you can let Python do it for you automatically with the correct syntax.

    You can use the apropos prefixes to get automatic conversion to integers with the following literals. These are valid for Python 2 and 3:

    Binary, prefix 0b

    >>> 0b11111
    31
    

    Octal, prefix 0o

    >>> 0o37
    31
    

    Hexadecimal, prefix 0x

    >>> 0x1f
    31
    

    This can be useful when describing binary flags, file permissions in code, or hex values for colors - for example, note no quotes:

    >>> 0b10101 # binary flags
    21
    >>> 0o755 # read, write, execute perms for owner, read & ex for group & others
    493
    >>> 0xffffff # the color, white, max values for red, green, and blue
    16777215
    

    Making ambiguous Python 2 octals compatible with Python 3

    If you see an integer that starts with a 0, in Python 2, this is (deprecated) octal syntax.

    >>> 037
    31
    

    It is bad because it looks like the value should be 37. So in Python 3, it now raises a SyntaxError:

    >>> 037
      File "<stdin>", line 1
        037
          ^
    SyntaxError: invalid token
    

    Convert your Python 2 octals to octals that work in both 2 and 3 with the 0o prefix:

    >>> 0o37
    31
    
    0 讨论(0)
  • 2020-11-21 04:46

    Use:

    >>> str_float = "545.2222"
    >>> float(str_float)
    545.2222
    >>> type(_) # Check its type
    <type 'float'>
    
    >>> str_int = "31"
    >>> int(str_int)
    31
    >>> type(_) # Check its type
    <type 'int'>
    
    0 讨论(0)
  • 2020-11-21 04:49

    for number and char together :

    string_for_int = "498 results should get"
    string_for_float = "498.45645765 results should get"
    

    first import re:

     import re
    
     #for get integer part:
     print(int(re.search(r'\d+', string_for_int).group())) #498
    
     #for get float part:
     print(float(re.search(r'\d+\.\d+', string_for_float).group())) #498.45645765
    

    for easy model :

    value1 = "10"
    value2 = "10.2"
    print(int(value1)) #10
    print(float(value2)) #10.2
    
    0 讨论(0)
  • 2020-11-21 04:49
    a = int(float(a)) if int(float(a)) == float(a) else float(a)
    
    0 讨论(0)
提交回复
热议问题