检查字符串是否可以在Python中表示为数字的最佳方法是什么?
我目前拥有的功能是:
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
Run Code Online (Sandbox Code Playgroud)
这不仅是丑陋而且缓慢,似乎很笨重.但是我没有找到更好的方法,因为调用float
main函数更糟糕.
我对他们编写的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),它会在某个时刻抛出异常吗?
当传入的值应该是一个容器时,你不仅检查容器,还检查其中的所有值?
那些像factorial这样的情况怎么样,传入的内容可以转换为int(例如浮点数),但这样做可能会失去精度?