首页 > 解决方案 > 正确使用 Try

问题描述

我遇到的问题是我不知道是否有更好的方法来判断一个字符串是否可以在 python 中转换为 int。

try: 
  tempScores = int(tempScores)
except ValueError:
  tempScores = 10

标签: pythoncastingtry-catch

解决方案


这是对的。根据 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 代码样式指南:命名约定


推荐阅读