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

后端 未结 29 2800
醉话见心
醉话见心 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: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 "", 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
    

提交回复
热议问题