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


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

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


当前回答

float(x) if '.' in x else int(x)

其他回答

本地化和逗号

对于引发异常的float(“545545.2222”)等情况,您应该考虑在数字的字符串表示中使用逗号的可能性。相反,使用区域设置中的方法将字符串转换为数字并正确解释逗号。一旦为所需的数字约定设置了区域设置,locale.atof方法将一步转换为浮点。

示例1——美国数字惯例

在美国和英国,逗号可以用作千位分隔符。在这个美式语言环境的示例中,逗号作为分隔符被正确处理:

>>> import locale
>>> a = u'545,545.2222'
>>> locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
'en_US.UTF-8'
>>> locale.atof(a)
545545.2222
>>> int(locale.atof(a))
545545
>>>

示例2——欧洲数字惯例

在世界上大多数国家,逗号用于小数点而不是句点。在这个法语区域设置的示例中,逗号被正确处理为十进制标记:

>>> import locale
>>> b = u'545,2222'
>>> locale.setlocale(locale.LC_ALL, 'fr_FR')
'fr_FR'
>>> locale.atof(b)
545.2222

locale.atoi方法也可用,但参数应为整数。

def num(s):
    try:
        return int(s)
    except ValueError:
        return float(s)

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

这是一个函数,它将根据提供的实际字符串是否像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

您可以使用json.loads:

>>> import json
>>> json.loads('123.456')
123.456
>>> type(_)
<class 'float'>
>>> 

正如你所看到的,它变成了一种浮子。