检查字符串是否为实数

发布于 2024-11-06 10:49:13 字数 107 浏览 1 评论 0原文

有没有一种快速方法来查找字符串是否为实数,而不是一次读取一个字符并对每个字符执行 isdigit() ?我希望能够测试浮点数,例如 0.03001

Is there a quick way to find if a string is a real number, short of reading it a character at a time and doing isdigit() on each character? I want to be able to test floating point numbers, for example 0.03001.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

南风几经秋 2024-11-13 10:49:13

如果您将浮点数表示为实数,则这应该可以工作:

def isfloat(str):
    try: 
        float(str)
    except ValueError: 
        return False
    return True

请注意,这将在内部仍然循环您的字符串,但这是不可避免的。

If you mean an float as a real number this should work:

def isfloat(str):
    try: 
        float(str)
    except ValueError: 
        return False
    return True

Note that this will internally still loop your string, but this is inevitable.

溇涏 2024-11-13 10:49:13
>>> a = "12345" # good number
>>> int(a)
12345
>>> b = "12345G" # bad number
>>> int(b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '12345G'

您可以这样做:

def isNumber(s):
    try:
        int(s)
    except ValueError:
        return False
    return True

如果您想要一个浮点数,请将 int 替换为 float (感谢 @cobbal)。

>>> a = "12345" # good number
>>> int(a)
12345
>>> b = "12345G" # bad number
>>> int(b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '12345G'

You can do that:

def isNumber(s):
    try:
        int(s)
    except ValueError:
        return False
    return True

If you want a float number, replace int by float (thanks to @cobbal).

不念旧人 2024-11-13 10:49:13

还有另一种使用正则表达式的方法:

import re

def is_float(str):
    if re.match(r"\d+\.*\d*", str):
        return True
    else:
        return False

There is also another way using regular expression:

import re

def is_float(str):
    if re.match(r"\d+\.*\d*", str):
        return True
    else:
        return False
遗弃M 2024-11-13 10:49:13

有一个更精确的实数正则表达式:

"^[-+]?[0-9]*\.?[0-9]+(e[-+]?[0-9]+)?$"

并且对此正则表达式进行一些检查:

realnum=re.compile("^[-+]?[0-9]*\.?[0-9]+(e[-+]?[0-9]+)?$")

["yes" if realnum.match(test) else "no" for test in ["12", "+12", "-12", "-3.14", ".314e1", "+.01e-12", "+22.134e+2"]]
['yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes']

["yes" if realnum.match(test) else "no" for test in ["..12", "+-12", "-12.", "-3.14p", ".314e1.9", "+. 01e-12", "+22.134e"]]
['no', 'no', 'no', 'no', 'no', 'no', 'no']

There is a more precise regexp of the real numbers:

"^[-+]?[0-9]*\.?[0-9]+(e[-+]?[0-9]+)?
quot;

And some check for this regexp:

realnum=re.compile("^[-+]?[0-9]*\.?[0-9]+(e[-+]?[0-9]+)?
quot;)

["yes" if realnum.match(test) else "no" for test in ["12", "+12", "-12", "-3.14", ".314e1", "+.01e-12", "+22.134e+2"]]
['yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes']

["yes" if realnum.match(test) else "no" for test in ["..12", "+-12", "-12.", "-3.14p", ".314e1.9", "+. 01e-12", "+22.134e"]]
['no', 'no', 'no', 'no', 'no', 'no', 'no']
幸福%小乖 2024-11-13 10:49:13

验证实数的方法:

def verify_real_number(item):
""" Method to find if an 'item'is real number"""

item = str(item).strip()
if not(item):
    return False
elif(item.isdigit()):
    return True
elif re.match(r"\d+\.*\d*", item) or re.match(r"-\d+\.*\d*", item):
    return True
else:
    return False

Method to verify real number:

def verify_real_number(item):
""" Method to find if an 'item'is real number"""

item = str(item).strip()
if not(item):
    return False
elif(item.isdigit()):
    return True
elif re.match(r"\d+\.*\d*", item) or re.match(r"-\d+\.*\d*", item):
    return True
else:
    return False
千柳 2024-11-13 10:49:13

定义一个函数来执行此操作是正确的方法,尽管遗憾的是 Python 尚未提供这样的函数。

我不喜欢使用 try ...除了这一点,因为我被灌输了“例外是针对特殊情况的”,而不是针对控制流的。

一行解决方案(如果您需要它,尽管效率较低,除了正则表达式答案)是

lambda x: all(n < 2 and i.isdigit() for n, i in enumerate(x.split('.')))

如果您将遇到写为 1..01< /code>,然后只需添加长度检查

lambda x: all(n < 2 and (i.isdigit() or len(i) == 0) for n, i in enumerate(x.split('.')))

Defining a function to do this is the right approach, although it's a shame that Python does not already provide such a function.

I'm not a fan of using try ... except for this, because it was drilled into me that "exceptions are for exceptional circumstances", and not for control flow.

A one-line solution (if you ever want it, although it is less efficient, except for the regex answers) is

lambda x: all(n < 2 and i.isdigit() for n, i in enumerate(x.split('.')))

If you are going to encounter decimals written as 1. or .01, then simply add a length check

lambda x: all(n < 2 and (i.isdigit() or len(i) == 0) for n, i in enumerate(x.split('.')))
給妳壹絲溫柔 2024-11-13 10:49:13

如果你想检查整数和浮点数,你可以看看这个

def isDigit(str):
    try:
        int(str) or float(str)
    except ValueError:
        return False
    return True

if you wanna check both integer and float numbers, you can check this out

def isDigit(str):
    try:
        int(str) or float(str)
    except ValueError:
        return False
    return True
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文