>>> float('123') 123.0 >>> float('nan') nan >>> float('nana') Traceback (most recent call last): File "<pyshell#97>", line 1, in <module> float('nana') ValueError: could not convert string to float: 'nana'
hahastudio
2014-08-17 16:45:23 +08:00
啊,Python 喜欢先试,后果另说 你大可以 try: ....n = float(input_str) # e.g. input_str = "123" except ValueError: ....n = float("nan") # or any other default value you want
对了,突然想起来,也许这个才是 LZ 最想要的: >>> from decimal import * >>> setcontext(ExtendedContext) >>> nan = Decimal("I'm not a number!") >>> nan Decimal('NaN') >>> print nan NaN