python - 正确使用 Try
问题描述
我遇到的问题是我不知道是否有更好的方法来判断一个字符串是否可以在 python 中转换为 int。
try:
tempScores = int(tempScores)
except ValueError:
tempScores = 10
解决方案
这是对的。根据 Python 约定,我只会在命名中使用下划线和单数(因为它是一个分数,而不是多个分数)temp_score
:.
例子:
for temp_score in [1, '2', '3e2', '4a', 'b5']:
try:
temp_score = int(temp_score)
except ValueError:
temp_score = 10
print(temp_score)
输出:
1
2
10
10
10
还请参见:
Python 文档:处理异常
Python 文档:TypeError
PEP 8 -- Python 代码样式指南:命名约定
推荐阅读
- npm - 运行 npm run dev 时 Laravel 7 中的 npm 错误
- r - 在同一粘贴语句中使用不同的分隔符 R
- python - 如何通过Python中的ascii代码判断另一个字符串的字符串前缀?
- go - 从 --go_out=plugins 切换到 -go-grpc_out PATH 问题
- python - 将 on_click 方法添加到使用 ipywidgets 创建的按钮
- python-3.x - 在 Python 中使用 configparser 进行部分检查的问题
- bash - Bash:查找具有特定扩展名的所有文件并根据每个文件中的第一行内容重命名它们
- javascript - 如何为 IE11 正确使用 babel/corejs3/webpack?
- oracle - 为oracle sql中的两个不同列添加条件where子句
- javascript - 使用过渡更改 hr 数据内容的颜色