Python正则表达式 |检查输入是否为浮点数
先决条件: Python中的正则表达式
给定一个输入,编写一个Python程序来检查给定的 Input 是否是浮点数。
例子:
Input: 1.20
Output: Floating point number
Input: -2.356
Output: Floating point number
Input: 0.2
Output: Floating point number
Input: -3
Output: Not a Floating point number
在这个程序中,我们使用了re 模块的search()
方法。
re.search() :此方法要么返回 None (如果模式不匹配),要么返回re.MatchObject
,其中包含有关字符串匹配部分的信息。此方法在第一次匹配后停止,因此它最适合测试正则表达式而不是提取数据。
让我们看看Python程序:
# Python program to check input is
# Floating point number or not
# import re module
# re module provides support
# for regular expressions
import re
# Make a regular expression for
# identifying Floating point number
regex = '[+-]?[0-9]+\.[0-9]+'
# Define a function to
# check Floating point number
def check(floatnum):
# pass the regular expression
# and the string in search() method
if(re.search(regex, floatnum)):
print("Floating point number")
else:
print("Not a Floating point number")
# Driver Code
if __name__ == '__main__' :
# Enter the floating point number
floatnum = "1.20"
# calling run function
check(floatnum)
floatnum = "-2.356"
check(floatnum)
floatnum = "0.2"
check(floatnum)
floatnum = "-3"
check(floatnum)
输出:
Floating point number
Floating point number
Floating point number
Not a Floating point number