Change language

Python Regular Expression | Check if input is floating point or not

| |

Given the input, write a Python program to check if the given input is a floating point number or not.

Examples :

  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 

In this program we are using the search() module re method.

re.search (): this method either returns None (if the pattern does not match) or re.MatchObject which contains information about the matching part of the string. This method stops after the first match, so it is better suited for validating regular expressions than retrieving data.

Let’s take a look at a Python program to do this:

# Python program to validate input
# Floating point number or not

 
# import re module

  
# re module provides support
# for regular expressions

import re

  
# Make regular expression for
# float definition

< code class = "plain"> regex = ’[+ -]? [0-9] +. [0-9 ] + ’

  
# Define a function for
# check floating point number

def check (floatnum ): 

 

# pass a regular expression

# and a string in the search () method

if (re.search (regex, floatnum)): 

print ( "Floating point number"

  

else

print ( " Not a Floating point number "

  

 
Driver code

if __ name__ = = ’__main__’

  

# Enter a floating point number

floatnum = "1.20"

  

# call the run function

  check (floatnum)

  

floatnum = "- 2.356 "

  check (floatnum)

 

floatnum = " 0.2 "

  check (floatnum)

 

floatnum = "- 3"

check (floatnum)

Exit:

 Floating point number Floating point number Floating point number Not a Floating point number