3 回答

TA貢獻1830條經驗 獲得超9個贊
我建議使用 try except 子句請求寬恕而不是許可方法:
str_a = 'foo'
str_b = '1.2'
def make_float(s):
try:
return float(s)
except ValueError:
return f'Can't make float of "{s}"'
>>> make_float(str_a)
Can't make float of "foo"
>>> make_float(str_b)
1.2

TA貢獻1775條經驗 獲得超8個贊
Try except 子句的形式如下:
try:
? ? # write your code
? ? pass
except Exception as e: # which can be ValueError, or other's exceptions
? ? # deal with Exception, and it can be called using the variable e
? ? print(f"Exception was {e}") # python >= 3.7
? ? pass
except Exception as e: # for dealing with other Exception
? ? pass
# ... as many exceptions you would need to handle
finally:
? ? # do something after dealing with the Exception
? ? pass

TA貢獻1815條經驗 獲得超13個贊
最簡單的方法就是嘗試將其變成浮動。
try:
float(str)
except ValueError:
# not float
else:
# is float
- 3 回答
- 0 關注
- 172 瀏覽
添加回答
舉報