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


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

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


当前回答

还有正则表达式,因为有时字符串在转换为数字之前必须准备好并规范化:

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

用法:

parseNumber('13,345')
> 13345.0

parseNumber('- 123 000')
> -123000.0

parseNumber('99999\n')
> 99999.0

顺便说一句,有些东西可以验证你有一个号码:

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

其他回答

这是对你的问题的另一种解释(提示:它很模糊)。你可能正在寻找这样的东西:

def parseIntOrFloat( aString ):
    return eval( aString )

它是这样工作的。。。

>>> parseIntOrFloat("545.2222")
545.22220000000004
>>> parseIntOrFloat("545")
545

理论上,存在注入漏洞。例如,字符串可以是“import os;os.art()”。然而,如果没有任何关于字符串来源的背景信息,理论上可能是推测。因为这个问题很模糊,所以根本不清楚这个漏洞是否真的存在。

你需要考虑四舍五入才能做到这一点。

即-int(5.1)=>5int(5.6)=>5——错误,应该是6,所以我们做int(5.6+0.5)=>6

def convert(n):
    try:
        return int(n)
    except ValueError:
        return float(n + 0.5)

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

如果您正在处理混合整数和浮点数,并希望以一致的方式处理混合数据,下面是我使用正确的docstring的解决方案:

def parse_num(candidate):
    """Parse string to number if possible
    It work equally well with negative and positive numbers, integers and floats.

    Args:
        candidate (str): string to convert

    Returns:
        float | int | None: float or int if possible otherwise None
    """
    try:
        float_value = float(candidate)
    except ValueError:
        return None

    # Optional part if you prefer int to float when decimal part is 0
    if float_value.is_integer():
        return int(float_value)
    # end of the optional part

    return float_value

# Test
candidates = ['34.77', '-13', 'jh', '8990', '76_3234_54']
res_list = list(map(parse_num, candidates))
print('Before:')
print(candidates)
print('After:')
print(res_list)

输出:

Before:
['34.77', '-13', 'jh', '8990', '76_3234_54']

After:
[34.77, -13, None, 8990, 76323454]