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

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

问题描述

检查字符串是否可以在 Python 中表示为数字的最佳方法是什么?

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

我现在拥有的功能是:

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

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

Which, not only is ugly and slow, but also 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

我对两者都有争议.

正则表达式或其他字符串解析方法会更丑、更慢.

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

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

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

  • 一个数字,如果数字有效
  • 状态代码(例如,通过 errno)或异常表明无法解析有效数字.

C(例如)通过多种方式解决了这个问题.Python 对其进行了清晰明确的布局.

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天全站免登陆