Is there a concise way of formatting a number, that on occasion can also be a string?
The number would normally be a float, but occasionally it's also denoted as the string "n/a".
I would like to format the float with a fixed number of decimals, but print the entire string in case it is not a number.
For instance:
var=3.145623 print("This is {0:.2f}".format(var)) >>>This is 3.14 ,but
var = "n/a" print("This is {0:.2f}".format(var)) >>> File "<stdin>", line 1, in <module> >>> ValueError: Unknown format code 'f' for object of type 'str' I am not surprised by the ValueError, but wonder if there is a concise way around it, ideally without an explicit if-statement.
if-elseis the most straightforward way... This is the problem you get when you deal with mixed types, and why you should avoid it when possible.floator the string"n/a"? It seems that is the real problem.