Python 如何检查字符串是否可以转换为浮点数

Python 如何检查字符串是否可以转换为浮点数

本文将着重讨论如何在Python中检查字符串是否可以转换为浮点数。

第一种方法是使用 float() 类型转换。我们将编写一个使用异常处理的函数,并检查给定的字符串是否可以转换成字符串,如果可以转换,则返回True,否则返回False。

给定数字或文本,方法 float() 返回一个浮点数。如果没有给出值或者给出一个空参数,它将返回0.0作为浮点值。

示例1

在这个示例中,我们输入一个字符串并检查是否可以使用 float() 类型转换为浮点数 –

def isFloat(s):
   try:
      float(s)
      return True
   except:
      return False

str1 = "36.9"
print("The given string is")

print(str1)
print("Checking if the given string can be converted into float")

res = isFloat(str1)
print(res)

输出

上述示例的输出如下所示−

The given string is
36.9
Checking if the given string can be converted into float
True

示例2

在下面给出的示例中,我们将采用与上面相同的程序,我们将采用不同的输入并检查它是否可以转换为浮点数。

def isFloat(s):
   try:
      float(s)
      return True
   except:
      return False

str1 = "Welcome"
print("The given string is")

print(str1)
print("Checking if the given string can be converted into float")

res = isFloat(str1)
print(res)

输出

上述示例的输出如下:

The given string is
Welcome
Checking if the given string can be converted into float
False

使用isdigit()和replace()方法

第二种方法是使用 isdigit()replace() 方法。我们将浮点数中的 . 替换为空格,并检查替换后的字符串是否都是数字。如果所有字符都是数字,则返回True,否则返回False。

示例1

在这个示例中,我们输入一个字符串,然后使用isdigit()和 replace() 方法检查是否可以转换为浮点数。

str1 = "69.3"
print("The give string is")

print(str1)
print("Checking if the given string can be converted into float")

res = str1.replace('.', '', 1).isdigit()
print(res)

输出

上述示例的输出结果如下所示 –

The give string is
69.3
Checking if the given string can be converted into float
True

示例2

在下面给出的示例中,我们采用与上述相同的程序,但是我们采用不同的输入,并检查它是否可以转换为浮点数 −

str1 = "Welcome"
print("The give string is")

print(str1)
print("Checking if the given string can be converted into float")

res = str1.replace('.', '', 1).isdigit()
print(res)

输出

上面示例的输出如下:

The give string is
Welcome
Checking if the given string can be converted into float
False

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程