如何检查字符串是否是Python中的数字(float)? [英] How do I check if a string is a number (float) in Python?

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

问题描述

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



我目前的功能是:

  def is_number (s):
try:
float(s)
返回True
,除了ValueError:
return False
pre>

这不仅是丑陋和慢,似乎笨重。但是我没有找到一个更好的方法,因为在主函数中调用 float 更糟糕。

解决方案


这不仅是丑陋和慢


< blockquote>

我对两者都提出异议。



一个正则表达式或其他字符串解析会比较慢。



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



问题是任何数值转换函数有两种




  • 一个数字,如果该数字有效

  • 状态代码errno)或异常,以显示无法解析有效的数字。



C(作为示例) 。



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


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.

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

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