Python – 檢查浮點數字符串
字串由字元組成,為了將其轉換為浮點數資料型別,Python 透過使用內建函式提供了多種方法。藉助這些內建函式,我們可以輕鬆地檢查浮點數字符串。本文將指導使用者學習如何檢查字串是否包含浮點值。為此,將演示三種驗證浮點數字符串的策略。isdigit() 方法也用於檢查給定字串是否僅包含數字。然後使用 count() 和 replace() 檢查字串是否包含小數和數字的其他字元。
方法
方法 1 - 使用 try-except 塊
方法 2 - 使用正則表示式
方法 3 - 使用 isdigit() 方法
方法 1:使用 try-except 塊檢查浮點數字符串的 Python 程式
函式使用字串變數定義,並使用 try-except 方法,print 語句返回“True”或“False”的值。
演算法
步驟 1 - 函式使用一個包含“str”變數的引數定義。
步驟 2 - 如果引數包含浮點值,則返回“True”,否則返回“false”。
步驟 3 - 函式內部使用 float() 方法將給定的字串轉換為浮點型別,成功後返回 true,否則返回 false。
步驟 4 - 輸入“str1”初始化為浮點數字符串值。
步驟 5 - 根據 str 的值,列印語句。
示例
#function is defined with one parameter as str def str_float(str1): try: int(str1) #returns false if it is an integer value return False except ValueError: #returns error if it is not a float value pass try: #float method is used to convert the given string to float float(str1) #returns True if it is a float value return True except ValueError: #returns false if it is not a float value return False #str is initialized with a float value str1 = "38.90" if str_float(str1): #if true this statement will be returned print("Yes! float string") else: #if false this statement will be returned print("No! float string ")
輸出
Yes! float string
方法 2:使用正則表示式檢查浮點數字符串的 Python 程式
函式定義正則表示式模式,其中包含給定輸入字串中可能包含的所有可能性,例如符號(+ 或 -)、整數(從 0 到多個)、指數和小數。
演算法
步驟 1 - 匯入“re”庫以使用正則表示式方法。
步驟 2 - 函式使用一個包含“str”變數的引數定義。
步驟 3 - 當字串為浮點數資料型別時,返回“True”,否則返回“false”。
步驟 4 - 函式內部使用 re.match() 方法查詢輸入字串與給定正則表示式之間的匹配項。
步驟 5 - 初始化包含浮點值的 stg 變數。
步驟 6 - 根據 str 的值,列印語句。
示例
#importing the re module import re #function is defined with one parameter as stg def str_float(stg): regular_exp = re.compile("r'^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$") if regular_exp.match(stg): if "." in string: return True else: return False else: return False#str is initialized with a float value stg = "38.90" if str_float(stg): #if true this statement will be returned print("Yes! float string") else: #if false this statement will be returned print("No! float string")
輸出
Yes! float string
方法 3:使用 isdigit() 方法檢查浮點數字符串的 Python 程式
演算法
步驟 1 - 函式使用一個包含“str”變數的引數定義。
步驟 2 - 布林函式用於在使用三個函式(即 isdigit()、count() 和 replace() 方法)檢查字串後返回值。
步驟 3 - 當字串為浮點數資料型別時,在前兩個條件下返回“True”,否則返回“false”。
步驟 4 - 輸入“str1”指定為浮點數字符串值。
步驟 5 - 最後,列印語句。
示例
# function is defined with one parameter as str def str_float(str1): if str1.isdigit(): return False else: try: float(str1) return True except ValueError: return False# str is initialized with a float value str1 = "38.90" if str_float(str1): # if true this statement will be returned print("Yes! float string") else: # if false this statement will be returned print("No! float string")
輸出
Yes! float string
結論
Python 程式專門用於最大程度地減少手動操作和錯誤。要簡單地檢查給定的字串輸入是否為浮點數,有多種方法。上面討論了一些方法,例如使用 try 和 except 方法以及使用 isdigit() 函式檢查浮點數字符串,當輸入為整數時,它也會返回 false。