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`. 23个回答

``````>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545
``````  ~Onlooker int(a) will give an error that the string isn't a valid integer: ValueError: invalid literal for int() with base 10: '545.222', but converting from a float to an int is a supported conversion.
2 年多之前 回复 Lotus＠ why not simply int(a) but int(float(a)) ?
2 年多之前 回复 perhaps? Floating point numbers are inherently imperfect for representing decimals. For more, see stackoverflow.com/q/21895756/931277 YaoRaoLov just wondering why there is '04' in the end? why not simply '00'? also my current version of python is not having '04'.

This is another method which deserves to be mentioned here, ast.literal_eval:

This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.

That is, a safe 'eval'

``````>>> import ast
>>> ast.literal_eval("545.2222")
545.2222
>>> ast.literal_eval("31")
31
`````` 2 年多之前 回复 from.. this is not a good solution to the problem. It works fine in Python 2, but the following happens in Python 3: python >>> import ast >>> ast.literal_eval('1-800-555-1212') -2566 >>> To clarify why this is a problem, if you want it to leave phone numbers alone and not assume they are mathematical expressions, then this approach is not for you.
2 年多之前 回复
``````def num(s):
try:
return int(s)
except ValueError:
return float(s)
`````` from.. You can nest another try to throw an exception when it's not convertible to float.
2 年多之前 回复 elliott.david You are completely correct, but there are times when you want the input to dictate which one it will be. Letting the input dictate which one can work nicely with duck-typing.
7 年多之前 回复 10.24 implicit mixing floats/ints might lead to subtle bugs due to possible loss of precision when working with floats or to different results for / operator on floats/ints. Depending on context it might be preferable to return either int or float, not both.
7 年多之前 回复

## 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
"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
``````

You think you know what numbers are? You are not so good as you think! Not big surprise.   larry*wei So true becomes 1, that is I inherited from C++ i think 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.

``````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
``````  7*4 you are right I guess I copied and paste from a functionality that I was raising a particular exception. will edit. thanks Memor.の Why would you raise in your except section if you are doing nothing there? float() would raise for you.
4 年多之前 回复

I am surprised nobody mentioned regex because sometimes string must be prepared and normalized before casting to number

``````import re
def parseNumber(value, as_int=False):
try:
number = float(re.sub('[^.\-\d]', '', value))
if as_int:
return int(number + 0.5)
else:
return number
except ValueError:
return float('nan')  # or None if you wish
``````

usage:

``````parseNumber('13,345')
> 13345.0

parseNumber('- 123 000')
> -123000.0

parseNumber('99999\n')
> 99999.0
``````

and by the way, something to verify you have a number:

``````import numbers
def is_number(value):
return isinstance(value, numbers.Number)
# will work with int, float, long, Decimal
``````

This is a corrected version of https://stackoverflow.com/a/33017514/5973334

This will try to parse a string and return either `int` or `float` depending on what the string represents. It might rise parsing exceptions or have some unexpected behaviour.

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

Use:

``````def num(s):
try:
for each in s:
yield int(each)
except ValueError:
yield float(each)
a = num(["123.55","345","44"])
print a.next()
print a.next()
``````

This is the most Pythonic way I could come up with.

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)
`````` 6 年多之前 回复 perhaps? Good point. That causes inflation, though, so Python 3 and other modern languages use banker's rounding. 