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


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

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


当前回答

对于数字和字符:

string_for_int = "498 results should get"
string_for_float = "498.45645765 results should get"

首次导入重新:

 import re

 # For getting the integer part:
 print(int(re.search(r'\d+', string_for_int).group())) #498

 # For getting the float part:
 print(float(re.search(r'\d+\.\d+', string_for_float).group())) #498.45645765

对于简单的模型:

value1 = "10"
value2 = "10.2"
print(int(value1)) # 10
print(float(value2)) # 10.2

其他回答

对于数字和字符:

string_for_int = "498 results should get"
string_for_float = "498.45645765 results should get"

首次导入重新:

 import re

 # For getting the integer part:
 print(int(re.search(r'\d+', string_for_int).group())) #498

 # For getting the float part:
 print(float(re.search(r'\d+\.\d+', string_for_float).group())) #498.45645765

对于简单的模型:

value1 = "10"
value2 = "10.2"
print(int(value1)) # 10
print(float(value2)) # 10.2

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'>
def num(s):
    try:
        return int(s)
    except ValueError:
        return float(s)

这是一个函数,它将根据提供的实际字符串是否像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 num(s):
    """num(s)
    num(3),num(3.7)-->3
    num('3')-->3, num('3.7')-->3.7
    num('3,700')-->ValueError
    num('3a'),num('a3'),-->ValueError
    num('3e4') --> 30000.0
    """
    try:
        return int(s)
    except ValueError:
        try:
            return float(s)
        except ValueError:
            raise ValueError('argument is not a string of number')