我用它来检查一个变量是否是数字,我也想检查它是否是一个浮点数.
if(width.isnumeric() == 1)
Run Code Online (Sandbox Code Playgroud)
Mar*_*oij 15
最简单的方法是将字符串转换为浮点数float():
>>> float('42.666')
42.666
Run Code Online (Sandbox Code Playgroud)
如果无法将其转换为浮点数,则会得到ValueError:
>>> 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'
Run Code Online (Sandbox Code Playgroud)
使用try/ exceptblock通常被认为是处理此问题的最佳方法:
try:
width = float(width)
except ValueError:
print('Width is not a number')
Run Code Online (Sandbox Code Playgroud)
注意你也可以用is_integer()a float()来检查它是否是一个整数:
>>> float('42.666').is_integer()
False
>>> float('42').is_integer()
True
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
输出:
>> is_float('string')
>> False
>> is_float('2')
>> False
>> is_float('2.0')
>> True
>> is_float('2.5')
>> True
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10091 次 |
| 最近记录: |