So I have a Python script that does a lot of calcualtions, but sometimes the "numbers" that are passed into the formulas are not always numbers. Sometimes they are strings.
So basically, what is an easier way to write these lines of code:
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)
So I already have a check that makes rate the value of 0 if the rate is None but will still fail if the value is "N/A" or any other value that is not a number. What is the Pythonic way of doing this calculation without try/except so that rate can be any value and the calculation will work as long as rate is some number?
CodePudding user response:
You can check for None, instance, and number-like strings:
if not rate or not str(rate).replace(".", "").isnumeric():
rate = 0
elif isinstance(rate, str):
if rate.isnumeric():
rate = int(rate)
elif rate.isdecimal():
rate = float(rate)
Test table
rate |
output |
|---|---|
'test' |
0 |
'test234' |
0 |
'123' |
123 |
None |
0 |
False |
0 |
123 |
123 |
'1.1/1' |
0 |
complex(1, 1) |
0 |
'1.1' |
1.1 |
If you're converting strictly to int (floats are 0):
if not rate or not str(rate).isnumeric():
rate = 0
elif isinstance(rate, str):
rate = int(rate)
if you want to round the float to an int:
if not rate:
rate = 0
elif isinstance(rate, str):
rate = int(float(rate))
CodePudding user response:
There's a method called isnumeric() which you can call on the string; see the documentation here. It returns True if all characters are numeric (digits or other Unicode characters with a numeric value, e.g. fractions), False otherwise. But my personal favourite is still try/except with a typecast to int or float.
