简体   繁体   English

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

[英]How to check if a string is a decimal/ float number?

I need to check if a string is of the form of a decimal/ float number.我需要检查一个字符串是否是十进制/浮点数的形式。

I have tried using isdigit() and isdecimal() and isnumeric(), but they don't work for float numbers.我曾尝试使用 isdigit() 和 isdecimal() 以及 isnumeric(),但它们不适用于浮点数。 I also can not use try: and convert to a float, because that will convert things like " 12.32" into floats, even though there is a leading white-space.我也不能使用 try: 并转换为浮点数,因为这会将诸如“12.32”之类的内容转换为浮点数,即使有一个前导空格。 If there is leading white-spaces, I need to be able to detect it and that means it is not a decimal.如果有前导空格,我需要能够检测到它,这意味着它不是小数。

I expect that "5.1211" returns true as a decimal, as well as "51231".我希望“5.1211”和“51231”以小数形式返回true。 However, something like "123.12312.2" should not return true, as well any input with white-space in it like " 123.12" or "123. 12 ".然而,像“123.12312.2”这样的东西不应该返回真,以及像“123.12”或“123.12”这样的任何带有空格的输入。

By no means am I suggesting this is the best way of doing things as I am a beginner myself, but, you could do something like: 我绝不是建议这样做,因为我本人还是新手,但这是最好的方法,但是,您可以执行以下操作:

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

This is very similar to @jthecoder 's answer however it also accounts for the white space. 这与@jthecoder的答案非常相似,但是它也考虑了空格。

EDIT: @jthecoder I didn't see the author mention strings ending with white spaces because it cuts off midline for me. 编辑:@jthecoder我没有看到作者提到以空格结尾的字符串,因为它为我切断了中线。 My code now meets every requirement of the author. 我的代码现在可以满足作者的所有要求。

This is a good use case for regular expressions . 这是正则表达式的好用例。

You can quickly test your regex patterns at https://pythex.org/ . 您可以通过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.")

Use a try catch loop, and see if it throws an error if you convert it. 使用try catch循环,如果将其转换,则查看它是否引发错误。 Sample code: 样例代码:

try: 
  num_if_float = float(your_str_here)
  str = true
except:
  float = false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM