如何检查一个字符串是否是一个数字(浮点数)? [英] How do I check if a string is a number (float)?

查看:156
本文介绍了如何检查一个字符串是否是一个数字(浮点数)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是最好的方法来检查一个字符串是否可以用Python中的数字表示?



我现在有的功能是:

$ $ $ $ $ $ c $ def> (b)
try:
float(s)
return True
除了ValueError:
返回False

不仅丑陋而且缓慢,看起来笨重。但是我还没找到更好的方法,因为在主函数中调用 float 更糟糕。

解决方案


其中,不仅丑陋而且缓慢
blockquote>

我会争执这两个。



正则表达式或其他字符串解析将是丑陋的和慢。

我不确定有什么比以上更快。它调用函数并返回。 Try / Catch不会引入太多开销,因为最常见的异常是在没有大量的堆栈搜索的情况下被捕获的。

问题是任何数字转换函数都有两种的结果


  • 一个数字(如果该数字有效)
  • 状态代码errno)或例外,以显示无法解析有效的数字。



C(以一个例子为例) 。 Python清楚明确地列出了它。



我认为你的代码是完美的。


What is the best possible way to check if a string can be represented as a number in Python?

The function I currently have right now is:

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

Which, not only is ugly and slow, seems clunky. However I haven't found a better method because calling float in the main function is even worse.

解决方案

Which, not only is ugly and slow

I'd dispute both.

A regex or other string parsing would be uglier and slower.

I'm not sure that anything much could be faster than the above. It calls the function and returns. Try/Catch doesn't introduce much overhead because the most common exception is caught without an extensive search of stack frames.

The issue is that any numeric conversion function has two kinds of results

  • A number, if the number is valid
  • A status code (e.g., via errno) or exception to show that no valid number could be parsed.

C (as an example) hacks around this a number of ways. Python lays it out clearly and explicitly.

I think your code for doing this is perfect.

这篇关于如何检查一个字符串是否是一个数字(浮点数)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆