python - 在这里使用嵌套的 try-except 可接受的 Python 样式
问题描述
我需要检查字符串price
是整数还是浮点数,并True
在这种情况下或False
其他情况下返回。
这个函数是用可接受的 Python 风格编写的吗?
def is_valid_price(price):
try:
int(price)
return True
except:
try:
float(price)
return True
except:
return False
如果没有,让它看起来像 Pythony 的最好方法是什么?
解决方案
绝对不是——except
不指定异常类很容易出现问题。
def is_valid_price(price):
try:
float(price)
return True
except ValueError:
return False
不需要使用 test int(price)
,因为如果字符串可以转换为int
,它也可以转换为浮点数。
推荐阅读
- python - 复杂的熊猫子设置;在多列中选择符合条件的行
- c++ - 为自定义迭代器专门化 std::copy
- mysql - R:如何从 MySQL 中正确获取特殊字符?
- anaconda - 查询 anaconda 包的目标平台
- powershell - 如何使用powershell将键/输入发送到没有登录用户的正在运行的进程?
- java - 从 URL 下载文件?
- node.js - 理解 fs.writeFileSync(path, data[, options]) Node.js
- python - 将 args 作为单元测试的一部分传递以测试 pyspark 脚本
- javascript - 选中一个复选框时,另一个复选框必须消失
- java - 数据绑定“错误:找不到符号类模型”