def is_float(string):
try:
return float(string) and '.' in string # True if string is a number contains a dot
except ValueError: # String is not a number
return False
>>> float('Not a float')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: 'Not a float'
使用try/except块通常被认为是处理此问题的最佳方法:
try:
width = float(width)
except ValueError:
print('Width is not a number')
输出:
最简单的方法是使用
float()
将字符串转换为浮点:如果无法将其转换为浮点,则会得到一个
ValueError
:使用
try
/except
块通常被认为是处理此问题的最佳方法:注意,您还可以对
float()
使用is_integer()
来检查它是否是整数:相关问题 更多 >
编程相关推荐