如何检查字符串是否表示浮点数

2024-05-16 01:02:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我用这个来检查一个变量是否是数字,我还想检查它是否是浮点数。

if(width.isnumeric() == 1)

Tags: if数字width浮点数isnumeric
2条回答
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

输出:

>> is_float('string')
>> False
>> is_float('2')
>> False
>> is_float('2.0')
>> True
>> is_float('2.5')
>> True

最简单的方法是使用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

相关问题 更多 >