如何将str转换为float?"545.2222" → 545.2222如何将str转换为int?"31" → 31


相反,请参见在Python中将整数转换为字符串和将浮点转换为字符串而不舍入。

请改为使用“如何将输入读取为数字?”?关闭重复问题,其中OP从用户输入中接收到字符串并立即想要转换它,或者希望输入(在3.x中)自动转换类型。


当前回答

用户codelogic和harley是正确的,但请记住,如果您知道字符串是整数(例如545),则可以调用int(“545”),而无需先强制转换为float。

如果字符串在列表中,也可以使用map函数。

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

只有当它们都是同一类型的时候才是好的。

其他回答

这是一个函数,它将根据提供的实际字符串是否像int或float,将任何对象(不仅仅是str)转换为int或floate。此外,如果它是同时具有__float和__int__方法的对象,则默认使用__float__

def conv_to_num(x, num_type='asis'):
    '''Converts an object to a number if possible.
    num_type: int, float, 'asis'
    Defaults to floating point in case of ambiguity.
    '''
    import numbers

    is_num, is_str, is_other = [False]*3

    if isinstance(x, numbers.Number):
        is_num = True
    elif isinstance(x, str):
        is_str = True

    is_other = not any([is_num, is_str])

    if is_num:
        res = x
    elif is_str:
        is_float, is_int, is_char = [False]*3
        try:
            res = float(x)
            if '.' in x:
                is_float = True
            else:
                is_int = True
        except ValueError:
            res = x
            is_char = True

    else:
        if num_type == 'asis':
            funcs = [int, float]
        else:
            funcs = [num_type]

        for func in funcs:
            try:
                res = func(x)
                break
            except TypeError:
                continue
        else:
            res = x

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

这是我所能想到的最具Python风格的方式。

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

要在Python中进行类型转换,请使用该类型的构造函数,将字符串(或您试图转换的任何值)作为参数传递。

例如:

>>>float("23.333")
   23.333

在幕后,Python正在调用对象__float__方法,该方法应返回参数的float表示。这特别强大,因为您可以使用__float__方法定义自己的类型(使用类),以便使用float(myobject)将其强制转换为float。

float(“545.2222”)和int(float(”545.2222“))