如何在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()**。我們將用空格替換浮點數中存在的“**.**”,並使用 **isdigit()** 檢查結果字串。如果所有字元都是數字,則返回 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

更新於:2022年12月7日

2K+ 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.