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