如何将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'>

其他回答

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

这个问题似乎有点过时了。但让我建议一个函数parseStr,它有类似的功能,即返回整数或浮点数,如果给定的ASCII字符串不能转换为任何一个,它将不受影响地返回。当然,代码可能会被调整为只执行您想要的操作:

   >>> import string
   >>> parseStr = lambda x: x.isalpha() and x or x.isdigit() and \
   ...                      int(x) or x.isalnum() and x or \
   ...                      len(set(string.punctuation).intersection(x)) == 1 and \
   ...                      x.count('.') == 1 and float(x) or x
   >>> parseStr('123')
   123
   >>> parseStr('123.3')
   123.3
   >>> parseStr('3HC1')
   '3HC1'
   >>> parseStr('12.e5')
   1200000.0
   >>> parseStr('12$5')
   '12$5'
   >>> parseStr('12.2.2')
   '12.2.2'

本地化和逗号

对于引发异常的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):
    """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')