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


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

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


当前回答

将字符串传递给此函数:

def string_to_number(str):
  if("." in str):
    try:
      res = float(str)
    except:
      res = str
  elif(str.isdigit()):
    res = int(str)
  else:
    res = str
  return(res)

它将根据传递的内容返回int、float或string。

int字符串

print(type(string_to_number("124")))
<class 'int'>

浮点数字符串

print(type(string_to_number("12.4")))
<class 'float'>

字符串

print(type(string_to_number("hello")))
<class 'str'>

看起来像浮点数的字符串

print(type(string_to_number("hel.lo")))
<class 'str'>

其他回答

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

>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545
float(x) if '.' in x else int(x)

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

如果您正在处理混合整数和浮点数,并希望以一致的方式处理混合数据,下面是我使用正确的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]