相关疑难解决方法(0)

如何检查字符串是否为数字(浮点数)?

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

我目前拥有的功能是:

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False
Run Code Online (Sandbox Code Playgroud)

这不仅是丑陋而且缓慢,似乎很笨重.但是我没有找到更好的方法,因为调用floatmain函数更糟糕.

python floating-point casting type-conversion

1519
推荐指数
21
解决办法
127万
查看次数

我应该在python函数/方法上做多少输入验证?

我对他们编写的Python中有多少前期验证感兴趣.

以下是一些简单函数的示例:

def factorial(num):
    """Computes the factorial of num."""

def isPalindrome(inputStr):
    """Tests to see if inputStr is the same backwards and forwards."""

def sum(nums):
    """Same as the built-in sum()... computes the sum of all the numbers passed in."""
Run Code Online (Sandbox Code Playgroud)

在开始计算之前检查输入值有多彻底,如何进行检查?如果输入有问题(例如,在同一模块中定义了BadInputException),是否会抛出某种专有异常?你刚刚开始你的计算,并认为如果传入错误的数据(例如,"asd"到factorial),它会在某个时刻抛出异常吗?

当传入的值应该是一个容器时,你不仅检查容器,还检查其中的所有值?

那些像f​​actorial这样的情况怎么样,传入的内容可以转换为int(例如浮点数),但这样做可能会失去精度?

python validation

15
推荐指数
3
解决办法
3513
查看次数