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

时间:2019-02-17 00:56:45

标签: python floating-point

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

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

我希望“ 5.1211”和“ 51231”一样返回十进制的true。但是,诸如“ 123.12312.2”之类的内容以及其中带有空格的任何输入(如“ 123.12”或“ 123. 12”)均不应返回true。

3 个答案:

答案 0 :(得分:1)

绝对不是我建议这是最好的做事方式,因为我本人还是新手,但是,您可以执行以下操作:

map.set(2, "x")

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

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

答案 1 :(得分:0)

这是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 :(得分:-1)

使用try catch循环,如果将其转换,则查看它是否引发错误。示例代码:

try: 
  num_if_float = float(your_str_here)
  str = true
except:
  float = false
相关问题