【问题标题】:How to check if a string is a decimal/ float number?如何检查字符串是否为十进制/浮点数?
【发布时间】:2019-02-17 09:52:06
【问题描述】:

我需要检查一个字符串是否是十进制/浮点数的形式。

我尝试过使用 isdigit() 和 isdecimal() 和 isnumeric(),但它们不适用于浮点数。我也不能使用 try: 并转换为浮点数,因为这会将诸如“12.32”之类的内容转换为浮点数,即使有一个前导空格。如果有前导空格,我需要能够检测到它,这意味着它不是小数。

我希望“5.1211”以小数形式返回 true,以及“51231”。然而,像“123.12312.2”这样的东西不应该返回真,以及像“123.12”或“123.12”这样的任何带有空格的输入。

【问题讨论】:

  • 如果您不想只接受float 接受的内容,则需要明确说明 可接受的内容。例如:.12 应该被接受吗? 12.? 1e6? +1.23? 123_456.789? −123(带有 Unicode 减号)?

标签: python floating-point


【解决方案1】:

这是regular expressions 的一个很好的用例。

您可以在https://pythex.org/ 快速测试您的正则表达式模式。

import re

def isfloat(item):

    # A float is a float
    if isinstance(item, float):
        return True

    # Ints are okay
    if isinstance(item, int):
        return True

   # Detect leading white-spaces
    if len(item) != len(item.strip()):
        return False

    # Some strings can represent floats or ints ( i.e. a decimal )
    if isinstance(item, str):
        # regex matching
        int_pattern = re.compile("^[0-9]*$")
        float_pattern = re.compile("^[0-9]*.[0-9]*$")
        if float_pattern.match(item) or int_pattern.match(item):
            return True
        else:
            return False

assert isfloat("5.1211") is True
assert isfloat("51231") is True
assert isfloat("123.12312.2") is False
assert isfloat(" 123.12") is False
assert isfloat("123.12 ") is False
print("isfloat() passed all tests.")

【讨论】:

  • 哇,我什至不知道这是一回事。谢谢你。
【解决方案2】:

我绝不是建议这是最好的做事方式,因为我自己是初学者,但是,您可以这样做:

try:
    if num[0] != " " and num[-1] != " ":
        num = float(num)
        is_float = True
except ValueError:
    is_float = False

这与@jthecoder 的答案非常相似,但它也考虑了空白。

编辑:@jthecoder 我没有看到作者提到以空格结尾的字符串,因为它切断了我的中线。我的代码现在满足了作者的所有要求。

【讨论】:

  • 总体上是好的方法,IMO。我还建议检查int(num) 是否可以过滤出适用于float() 但实际上是整数值的情况(因此在技术上不是floats)。
  • 谢谢,这是我的第一个答案 :) 我没有包括在内,因为在最初的问题中,它说您希望将诸如“51231”之类的数字作为浮点数返回 true。
猜你喜欢
  • 2017-06-14
  • 2012-09-10
  • 2012-07-20
  • 1970-01-01
  • 1970-01-01
  • 2018-12-19
  • 2018-03-08
  • 2016-06-18
相关资源
最近更新 更多