如何在 Python 中将字符串解析为 float 或 int?

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.

转载于:https://stackoverflow.com/questions/379906/how-do-i-parse-a-string-to-a-float-or-int-in-python

csdnceshi77
狐狸.fox As a general rule, if you have an object in Python, and want to convert to that type of object, call type(my_object) on it. The result can usually be called as a function to do the conversion. For instance type(100) results in int, so you can call int(my_object) to try convert my_object to an integer. This doesn't always work, but is a good "first guess" when coding.
大约 2 年之前 回复

23个回答

>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545
csdnceshi72
谁还没个明天 You should handle ValueError if you want to be safe
接近 2 年之前 回复
csdnceshi55
~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 年多之前 回复
csdnceshi53
Lotus@ why not simply int(a) but int(float(a)) ?
2 年多之前 回复
csdnceshi57
perhaps? Floating point numbers are inherently imperfect for representing decimals. For more, see stackoverflow.com/q/21895756/931277
接近 3 年之前 回复
csdnceshi69
YaoRaoLov just wondering why there is '04' in the end? why not simply '00'? also my current version of python is not having '04'.
接近 3 年之前 回复

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
weixin_41568183
零零乙 Yeah, that's a good point and users should beware. The behaviour was originally modified in order to address some issues with parsing of complex literals. It's arguably a bug in ast.literal_eval, and has been discussed here.
2 年多之前 回复
weixin_41568174
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)
weixin_41568174
from.. You can nest another try to throw an exception when it's not convertible to float.
2 年多之前 回复
csdnceshi63
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 年多之前 回复
weixin_41568131
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
0x3fade               True         Hexadecimal
"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
"(1)"                 False        Parenthesis is bad

You think you know what numbers are? You are not so good as you think! Not big surprise.

weixin_41568184
叼花硬汉 good one, 四 is also chinese (something unrelated :))
接近 2 年之前 回复
csdnceshi72
谁还没个明天 No. In Python, True is cocerced to float value 1 when passed to float(...), so therefore true is convertable to float. False is coerced to 0, which is also a float. This type coercion has nothing to do with C++. Your ancient tomes aren't ancient enough, so discard them and FindOutChristianityNow. He will convert your datatypes in ways that benefit everyone, rather than just the in group clique.
接近 2 年之前 回复
csdnceshi65
larry*wei So true becomes 1, that is I inherited from C++ i think
接近 2 年之前 回复
csdnceshi78
程序go Please, consider renaming your function to convertibleToFloat or something similar (current name seems confusing, at least to me).
接近 4 年之前 回复

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.

csdnceshi70
笑故挽风 list(map(float, x)) for python 3...
接近 2 年之前 回复
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
csdnceshi50
三生石@ 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][1].
大约 3 年之前 回复
csdnceshi74
7*4 you are right I guess I copied and paste from a functionality that I was raising a particular exception. will edit. thanks
接近 4 年之前 回复
csdnceshi71
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)
weixin_41568110
七度&光 This answer is wrong (as originally written). It muddles the two cases of int and float. And it will give an exception, when n is a string, as OP desired. Maybe you meant: When an int result is desired, round should be done AFTER conversion to float. If the function should ALWAYS return an int, then you don't need the except part -- the entire function body can be int(round(float(input))). If the function should return an int if possible, otherwise a float, then javier's original solution is correct!
6 年多之前 回复
csdnceshi57
perhaps? Good point. That causes inflation, though, so Python 3 and other modern languages use banker's rounding.
接近 8 年之前 回复
共23条数据 1 3 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问