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


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

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


当前回答

这是龙猫的答案的修正版。

这将尝试解析字符串,并根据字符串表示的内容返回int或float。它可能会引发解析异常或出现一些意外行为。

  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

其他回答

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

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

将字符串传递给此函数:

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

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风格的方式。

a = int(float(a)) if int(float(a)) == float(a) else float(a)

如果您不想使用第三方模块,以下可能是最可靠的解决方案:

def string_to_int_or_float(s):
    try:
        f = float(s) # replace s with str(s) if you are not sure that s is a string
    except ValueError:
        print("Provided string '" + s + "' is not interpretable as a literal number.")
        raise
    try:
        i = int(str(f).rstrip('0').rstrip('.'))
    except:
        return f
    return i

它可能不是最快的,但在许多其他解决方案失败的情况下,它可以正确处理字面数字,例如:

>>> string_to_int_or_float('789.')
789
>>> string_to_int_or_float('789.0')
789
>>> string_to_int_or_float('12.3e2')
1230
>>> string_to_int_or_float('12.3e-2')
0.123
>>> string_to_int_or_float('4560e-1')
456
>>> string_to_int_or_float('4560e-2')
45.6