检查Python字符串是否为数字而不使用try/except的最简单方法?



我有一个Python脚本,它做了很多计算,但有时数字"传入公式的并不总是数字。有时是字符串。

那么基本上,写这些代码行更简单的方法是什么呢?

units = 0 if math.isnan(UNITS) else OPH_UNITS
# the rate here could be "N/A" so the line below fails with: must be real number, not str
rate = 0 if not rate else rate
total = total + ((rate * units) * factor)

所以我已经有了一个检查,如果速率为None,则rate的值为0,但如果值为"N/a "或者其他非数字的值。在没有try/except的情况下,做这个计算的python方法是什么?这样rate可以是任何值,只要rate是某个数字,计算就会工作?

您可以检查None, instance和类似数字的字符串:

if not rate or not str(rate).replace(".", "").isnumeric():
rate = 0
elif isinstance(rate, str):
if rate.isnumeric():
rate = int(rate)
elif rate.replace(".", "").isnumeric():
rate = float(rate)

测试表

<表类>rate输出typetbody><<tr>'test'0<class 'int'>'test123'0<class 'int'>'123'123<class 'int'>None0<class 'int'>False0<class 'int'>123123<class 'int'>'1.1/1'0<class 'int'>complex(1, 1)0<class 'int'>'1.1'1.1<class 'float'>1.11.1<class 'float'>

你可以在字符串上调用isnumeric()方法;请参阅此处的文档。如果所有字符都是数字(数字或其他具有数值的Unicode字符,例如分数),则返回True,否则返回False。但我个人最喜欢的仍然是try/except,类型转换为intfloat

最新更新