如何检查一个字符串是否为十进制/浮点数?

4
我需要检查一个字符串是否为十进制/浮点数的形式。
我尝试使用isdigit()、isdecimal()和isnumeric(),但它们不能用于浮点数。我也不能使用try:并转换为浮点数,因为这会将像"12.32"这样的东西转换为浮点数,即使有前导空格。如果有前导空格,我需要能够检测到它,这意味着它不是十进制数。
我希望"5.1211"作为十进制数返回true,以及"51231"。然而,像"123.12312.2"这样的内容不应该返回true,以及任何带有空格的输入,如"123.12"或"123. 12"。

如果您不想仅接受float所接受的内容,则需要明确指定哪些内容是可接受的。例如:应该接受.12吗?12.1e6+1.23123_456.789−123 (带有Unicode减号) ? - Mark Dickinson
1个回答

3
这是一个适合使用正则表达式的例子。你可以通过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.")

哇,我甚至不知道这是一件事。谢谢你告诉我。 - Bemjamin Zhuo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接