如何在 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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP