我正在使用这个方法来检查一个变量是否为数字,同时我也想检查它是否为浮点数。
if(width.isnumeric() == 1)
最简单的方法是使用float()
将字符串转换为浮点数:
>>> float('42.666')
42.666
如果无法转换为浮点数,则会出现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'
使用 try
/except
语句块通常被认为是处理此类问题的最佳方式:
try:
width = float(width)
except ValueError:
print('Width is not a number')
请注意,您还可以在float()
上使用is_integer()
来检查它是否为整数:
>>> float('42.666').is_integer()
False
>>> float('42').is_integer()
True
is_integer()
来区分整数和浮点数是一个不错的方法。 - mhawkedef 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
输出:
>> is_float('string')
>> False
>> is_float('2')
>> False
>> is_float('2.0')
>> True
>> is_float('2.5')
>> True
>>> "124".replace(".", "", 1).isdigit()
True
>>> "12.4".replace(".", "", 1).isdigit()
True
>>> "12..4".replace(".", "", 1).isdigit()
False
>>> "192.168.1.1".replace(".", "", 1).isdigit()
False
3
和3.5
放在同一个检查中吗? - zondowidth.isnumeric()
是一个暗示width
是一个字符串。他并不是在检查一个真实的数字是否为浮点数;他是在检查一个字符串是否可以转换为浮点数。 - zondo1.0
是float
类型,但它具有整数值(与fractions.Fraction(10,5)
一样) --- 对于你的目的来说,它们是否属于“浮点数”? - Kevin J. Chase